Friday, 30 September 2022

Do we still need LiveData in Jetpack Compose, or we can just use Compose State?

I have a ViewModel as below that has both LiveData and Compose State

@Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T: Any>(value: T) : LiveData<T>(value) {

    override fun getValue(): T = super.getValue() as T
    public override fun setValue(value: T) = super.setValue(value)
    public override fun postValue(value: T) = super.postValue(value)
}

class MainViewModel: ViewModel() {

    private val _liveData: SafeMutableLiveData<Int> = SafeMutableLiveData(0)
    val liveData: SafeMutableLiveData<Int> = _liveData

    var composeState: Int by mutableStateOf(0)

    fun triggerLiveData() {
        _liveData.value = _liveData.value + 1
        composeState++
    }
}

Both composeState and liveData above do the same thing and used by my Compose View as below

    @Composable
    fun MyComposeView(viewModel: MainViewModel) {
        val liveDataResult = viewModel.liveData.observeAsState()
        Column {

            Button(onClick = { viewModel.triggerLiveData() }) {
                Text(text = "Click Me!")
            }

            Text(text = "${viewModel.number} ${liveDataResult.value}")
        }
    }

I notice both the LiveData and Compose State values are

  • Preserved when orientation change.
  • Destroy when OnRestoration (app killed by the system).
  • Don't update the compose view, i.e. when it's activity/fragment container no longer exists (e.g. won't crash the app like rxjava callback when the fragment/activity is gone).

It seems like LiveData doesn't add more benefit than Compose State. It has more complications like we need to add .observeAsState() etc.

Is there any scenario that we should still use LiveData instead of Compose State variable in our View Model when we program in Jetpack Compose only?



from Do we still need LiveData in Jetpack Compose, or we can just use Compose State?

No comments:

Post a Comment