Simple event structure for single-time events like showing popup observed from LiveData
Taken from JoseAlcerreca's medium post and packaged into gradle library for ease of use.
Step 1. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.alperenbabagil:EventForLiveData:1.2.1'
}
Wrap your data with Event<T>
class. Then use it in LiveData
val observeMe : LiveData<Event<MyAwesomeModel>>
Then observe your viewModel with EventObserver<T>
viewModel.observeMe.observe(this,EventObserver{ myAwesomeModel ->
// Every Event instance observed here once
})
or just use observeEvent
extension function of LiveData
viewModel.observeMe.observeEvent(this){ myAwesomeModel ->
// Every Event instance observed here once
}
even shorter use observeEvent
extension function of LifecycleOwner
(Activity,Fragment etc.).
Just call observeEvent
method in your LifecycleOwner:
observeEvent.(viewModel.observeMe){ myAwesomeModel ->
// Every Event instance observed here once
}