简体   繁体   中英

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, ie when it's activity/fragment container no longer exists (eg 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?

Both Compose's MutableState and Kotlin's MutableStateFlow may be used to replace MutableLiveData in a ViewModel.

If your ViewModel is supposed to be truly agnostic from the view system, then StateFlow is probably a better option than Compose's State . If you don't care about supporting other kinds of view systems than Compose, then you can use Compose's State .

One important thing to consider though , is that Compose's State is not Lifecycle-aware by itself. To make it Lifecycle-aware on Android, it is mandatory to use LiveData.observeAsState() or Flow.collectAsStateWithLifecycle() from a composable function outside of the ViewModel. So if your state is connected to a data source performing active work while being observed, commonly called a "cold" flow, then you must expose it as a LiveData or StateFlow from your ViewModel and observe it in a Lifecycle-aware manner using these functions, otherwise the data source will continue performing work even when the screen is not visible.

I see the next cases to use the LiveData still:

  1. You are using ViewModel with a non-Compose View at the same time as with a Compose View. This is possible to face it in an old project which is under migration to Compose, for example, if you have a shared ViewModel for an old View and Compose View.
  2. You have LiveData in other layers of the project. For example, you observe data from Room using LiveData.
  3. You need to use a transformation API for LiveData map , switchMap , or other benefits.

But Google doesn't have strict requirements for which type of observable to use, it mostly depends on your project (requirements, architecture, etc.) and preferences. Google says apart from Compose State you can use LiveData, RxJava, Kotlin Flows, and just to convert it to State https://developer.android.com/jetpack/compose/state#use-other-types-of-state-in-jetpack-compose

If we are saying about your example then I believe you don't need to use LiveData in such trivial cases.

In my opinion, looking at how Google actively promotes JetPack Compose and Kotlin Flows most likely that LiveData can be deprecated at some point in the near future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM