Created
April 21, 2019 08:24
Star
You must be signed in to star a gist
Android Livedata Observe Once Only (Kotlin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer<T>) { | |
observe(lifecycleOwner, object : Observer<T> { | |
override fun onChanged(t: T?) { | |
observer.onChanged(t) | |
removeObserver(this) | |
} | |
}) | |
} | |
//Using | |
liveData.observeOnce(this, Observer<Password> { | |
if (it != null) { | |
// do something | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val liveData = viewModel.showSnackBar("Hi everyone") | |
liveData.observe(this, object: Observer<String> { | |
override fun onChanged(text: String?) { | |
liveData.removeObserver(this) | |
} | |
}) |
Great, thanks for the reply!
Good Solution David, that Only work for me. All other solution not work for me and I didn't know why.
@kobeumut Thank you for this useful code
thanks for the solution, however for non-nullable variables with initial value, or for patterns with removing observer on certain conditions, this is helpful
fun <T> LiveData<T>.observeUntil(
owner: LifecycleOwner,
predicate: (T) -> Boolean,
observer: (T) -> Unit
) {
observe(owner, object: Observer<T> {
override fun onChanged(value: T) {
if(predicate(value)) {
removeObserver(this)
}
observer(value)
}
})
}
this can be used as:
val mutLiveData = MutableLiveData(0)
mutLiveData.observeUntil(viewLifecycleOwner, { it == 10}) {
/* code goes here... */
}
Nice!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello David, I'm not sure what is the best solution for it but you are right. And also your script that wrote above is going to work properly.