- app/FakeActivity.kt
class FakeActivity : AppCompatActivity() {
private val viewModel: TestMyLiveData by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val button = Button(this)
setContentView(button)
button.setOnClickListener {
viewModel.changeData(55)
}
viewModel.data.observe(this) {
button.text = "$it"
}
}
}
/**
* 避免了每次再 XxxViewModel 中都需要将 MutableLiveData 转成 LiveData 向外暴露的问题
*/
class TestMyLiveData : BaseViewModel() {
val data = MyLiveData(MutableLiveData(0))
fun changeData(n: Int) {
setValue(data, n)
}
}
- lib-internal/BaseViewModel.kt
/**
* 放在和 MyLiveData 同一个 module 中
*/
abstract class BaseViewModel : ViewModel() {
protected fun <T> postValue(data: MyLiveData<T>, value: T) {
data.postValue(value)
}
protected fun <T> setValue(data: MyLiveData<T>, value: T) {
data.setValue(value)
}
}
- lib-internal/MyLiveData.kt
/**
* 需要放在单独的 module 中
*/
class MyLiveData<T>(private val data: MutableLiveData<T?>) {
internal fun postValue(value: T) {
data.postValue(value)
}
internal fun setValue(value: T) {
data.setValue(value)
}
fun observe(owner: LifecycleOwner, observer: Observer<in T?>) {
data.observe(owner, observer)
}
}
原始写法:
class TestViewModel : ViewModel() {
//为保证对外暴露的LiveData不可变,增加一个状态就要添加两个LiveData变量
private val _pageState: MutableLiveData<PageState> = MutableLiveData()
val pageState: LiveData<PageState> = _pageState
}
网友评论