icerockdev / moko-mvvm

Model-View-ViewModel architecture components for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
997 stars 95 forks source link

Question: Using ViewModel + LiveData without MvvmActivity #104

Closed dima-ko closed 3 years ago

dima-ko commented 3 years ago

Hey, guys. I want to use your MVVM approach but without MvvmActivity/MvvmFragment. Is it possible to just observe LiveData? Will it bring any memory leaks? Should I call ViewModel.onCleared() at some point? Here is the example code:

Screenshot 2021-02-12 at 20 17 42
Alex009 commented 3 years ago

hi!

ViewModel in moko-mvvm for android just subclass of ViewModel from android architecture components. so all same as in AAC. https://developer.android.com/topic/libraries/architecture/viewmodel

you should not call onCleared manually - it will be called by android. but in your code invalid usage of livedata. you should call ld() function to transform common livedata into android livedata with observe(lifecycle, observer) function.

viewModel.pageResultLD.ld().observe(this, Observer<Result<List<CountryRow>>> { result ->
    // update UI
})

in this case you should not removeObserver manually, because it will be controlled by AAC livedata logic with lifecycle.

also you can use

viewModel.pageResultLD.bind(this) { result ->
    // update UI
})

it call ld().observe inside