Several Kotlin extensions for convenient use of ViewModel and LiveData
Add repository to your root build.gradle
repositories {
jcenter()
}
dependencies {
implementation 'com.idapgroup:lifecycle-ktx:1.0.3'
}
class ExampleActivity : AppCompatActivity() {
private lateinit var factory: ViewModelProvider.Factory
val viewModel: ExampleViewModel by lazyViewModel { factory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
observe(viewModel.liveData, ::observeLiveData)
}
private fun observeLiveData(value: String) {
// do something with value
}
}
class ExampleViewModel : ViewModel() {
val liveData = mutableLiveDataOf("1")
}
SingleLiveEvent - class that extends MutableLiveData and emits value only once for observer. Multiple observers registered but only one will be notified of changes.
For Dagger users added ViewModelProvider.Factory class and @ViewModelKey annotation.