简单的说明一下
M model 层 做数据请求,处理
V view层 简单来说就是所有的Activit的View或者Fragment的View
VM viewModel 上联Model 下联view
简单来说 就是V 要显示什么。告诉VM .VM告诉M .M拿到数据给到VM,VM再把数据给到V
或者 M数据有变化。告诉VM .VM传递给V
VM 是如何通知V的呢。这里我使用的是MutableLiveData<>()这个类
View 所有要要到数据对象都在VM声明。View持有VM.View层通过observe观察数据变化。如下图
Model 如何VM交互呢。我这边是通过接口完成
VM 持有Model对象。VM主动调用Model层方法。对于一些异步操作,我这里通常使用的接口
VM设置接口给Mode。其实也可以用kotlin协程来处理
我的总体思路就是 view层作为主动方 主动去调用VM层方法。VM层去调用Model层的方法
View 持有VM 对象。VM持有Model 对象
这是我的项目结构
这是View基类
abstract class BaseActivity<VM : ViewModel, VB : ViewBinding>(
private val viewModelClass: Class<VM>?,
private val inflate: (LayoutInflater) -> VB,
) : AppCompatActivity() {
protected lateinit var binding: VB
protected val loadingDialog by lazy {
LoadingDialog()
}
protected val viewModel by lazy {
val viewModelProvider = ViewModelProvider(this)
viewModelClass?.let {
viewModelProvider[it]
}
}
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
binding = inflate(layoutInflater)
setContentView(binding.root)
PublicViewModel.tokenState.observe(this) {
if ((PublicViewModel.TokenState.INVALID == it) and (PublicViewModel.isLoginEd.value == true)) {
startActivity(Intent(this, LoginActivity::class.java))
finish()
}
}
PublicViewModel.loadingState.observe(this) {
if (it == PublicViewModel.LoadingState.LOAD_SHOW) {
loadingDialog.show(supportFragmentManager)
PublicViewModel.loadingState.value= PublicViewModel.LoadingState.LOADING
} else if (it == PublicViewModel.LoadingState.LOAD_HIDE) {
loadingDialog.dismissAllowingStateLoss()
PublicViewModel.loadingState.value= PublicViewModel.LoadingState.IDEAL
}
}
toRefreshUI(viewModel)
}
abstract fun toRefreshUI(viedModel: VM?)
override fun onDestroy() {
super.onDestroy()
if (PublicViewModel.loadingState.value == PublicViewModel.LoadingState.LOADING) {
loadingDialog.dismissAllowingStateLoss()
PublicViewModel.loadingState.value= PublicViewModel.LoadingState.IDEAL
}
}
}
viewModel 的基类
package com.zhongjinkang.rhythm.viewModel
import androidx.lifecycle.*
import com.zhongjinkang.rhythm.Model.BaseModel
//VM 层
open abstract class BaseViewModel<Model:BaseModel>(
protected val model:Model?,
): ViewModel() {
//
// override fun addCloseable(closeable: Closeable) {
// super.addCloseable(closeable)
// }
//
// override fun onCleared() {
// super.onCleared()
// }
//
// //生命周期管理
// fun onAny(owner: LifecycleOwner?, event: Lifecycle.Event?) {
//
// }
}
这是项目地址。感兴趣的可以看一下