MVP-VM
M:model层,即数据层
V:视图层,Activity/Fragment为代表
P:控制层,业务处理
VM:viewmodel 与databinding 配合使用
P层持有V层和VM层,处理所有的业务逻辑,P层可控制V层的显示,P层通过VM层获取到数据并可以进行处理,最终控制V,
VM层获取到Model,可以通过DataBinding显示V,减少P层控制V
P:
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.Observer
/**
16 * @ClassName: BasePresenter
17 * @Description: java类作用描述
18 * @Author: lyf
19 * @Date: 2019-05-27 16:46
20 */
abstract class BasePresenter<V : BaseView, VM : BaseViewModel>(
var mView: V?,
var mViewModel: VM?,
owner: LifecycleOwner
) {
init {
this.initCommon(owner)
this.start(owner)
}
/**
* 统一显示加载框
*/
private fun initCommon(owner: LifecycleOwner) {
mViewModel?.loadLiveData?.observe(owner, Observer {
when (it) {
true -> {
mView?.showLoading()
}
else -> {
mView?.hideLoading()
}
}
})
}
protected abstract fun start(owner: LifecycleOwner)
fun onDestroy() {
mView = null
mViewModel?.onCleared()
mViewModel = null
}
}
V:
package com.example.mvp_vm.base
/**
16 * @ClassName: BaseView
17 * @Description: java类作用描述
18 * @Author: lyf
19 * @Date: 2019-05-27 16:46
20 */
interface BaseView {
/**
* 显示网络请求loading
*/
fun showLoading()
/**
* 隐藏网络请求loading
*/
fun hideLoading()
}
VM
package com.example.mvp_vm
import android.arch.lifecycle.MutableLiveData
import com.example.mvp_vm.base.BaseViewModel
import kotlinx.coroutines.*
import java.util.*
/**
16 * @ClassName: HomeViewModel
17 * @Description: java类作用描述
18 * @Author: lyf
19 * @Date: 2019-05-27 23:45
20 */
class HomeViewModel : BaseViewModel() {
private val random by lazy { Random() }
val textLiveData by lazy { MutableLiveData<TextModel>() }
/**
* 模拟获取网络数据
*/
fun getTextData() = runBlocking {
GlobalScope.launch(Dispatchers.Main) {
loadLiveData.value = true
delay(1000)
val text = TextModel("来了,老弟" + random.nextInt(100))
textLiveData.value = text
loadLiveData.value = false
}
}
}
demo详情https://github.com/tzz2015/MVP-VM