Android架构组件拥有生命周期的自动管理和数据解耦等优秀的功能,能够将传统MVP架构进行替换。在使用架构组件的过程中,我采用的方式是首先完成基础类
T 表示对应的retrofit service类型
abstract class BaseViewModel<T>(application: Application) : AndroidViewModel(application) {
之后针对Retrofit中的不同Service interface,继承并实现具体的viewmodel类,并针对每个service接口,需要编写一个liveData字段和对应的get或post方法提供给app层调用,同时对应的方法可能会存在三种类型:
package com.xxx.xxx.architecture.xxx
import android.app.Application
import android.arch.lifecycle.MediatorLiveData
import com.baseproject.architecture.BaseViewModel
import com.xxx.xxx.appbase.BaseAppLiveDataObserver
/**
* This file is generated by kapt, please do not edit this file */
open class BaseAnchorServiceViewModel(application: Application) : BaseViewModel<AnchorService>(application) {
val getHotAnchorListLiveData: MediatorLiveData<kotlin.collections.List<SearchHotAnchorModel>> by lazy { MediatorLiveData<kotlin.collections.List<SearchHotAnchorModel>>() }
fun getHotAnchorList() {
mService.getHotAnchorList().subscribe(BaseAppLiveDataObserver(getHotAnchorListLiveData))
}
}
val getUserAssetsLiveData: MediatorLiveData<UserAssetsModel> by lazy { MediatorLiveData<UserAssetsModel>() }
fun getUserAssets() {
object : BaseAppNetworkBoundResource<UserAssetsModel>(getUserAssetsLiveData) {
override fun doApiCall(): Observable<UserAssetsModel> {
return mService.getUserAssets()}}
}
val postRewardReceiveLiveData: MediatorLiveData<PostRewardReceiveModel> by lazy { MediatorLiveData<PostRewardReceiveModel>() }
fun postRewardReceive(reward_ids: List<Int>, anchor_id: String) {
val params = BaseJSONObject().put("reward_ids",reward_ids).put("anchor_id",anchor_id)
mService.postRewardReceive(RequestBody.create(MediaType.parse("application/json"), params.toString())).subscribe(BaseAppLiveDataObserver(postRewardReceiveLiveData))
}
不同的方式有很多共同之处,因此我采用kapt注解的方式一键生成相关代码,大大优化了开发效率,项目地址:
https://github.com/huanle19891345/kapt_viewmodel
欢迎指教