Android ViewModel 中避免每次都需要将 MutableLiveData 转成 LiveData 向外暴露的解决思路

  • 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  postValue(data: MyLiveData, value: T) {
        data.postValue(value)
    }

    protected fun  setValue(data: MyLiveData, value: T) {
        data.setValue(value)
    }

}
  • lib-internal/MyLiveData.kt
/**
 * 需要放在单独的 module 中
 */
class MyLiveData(private val data: MutableLiveData) {

    internal fun postValue(value: T) {
        data.postValue(value)
    }

    internal fun setValue(value: T) {
        data.setValue(value)
    }

    fun observe(owner: LifecycleOwner, observer: Observer) {
        data.observe(owner, observer)
    }

}

原始写法:

class TestViewModel : ViewModel() {
    //为保证对外暴露的LiveData不可变,增加一个状态就要添加两个LiveData变量
    private val _pageState: MutableLiveData = MutableLiveData()
    val pageState: LiveData = _pageState
}

你可能感兴趣的:(Android ViewModel 中避免每次都需要将 MutableLiveData 转成 LiveData 向外暴露的解决思路)