-
-
Save MossoIsai/72d1d1e1421cf2e1707587cd625d3257 to your computer and use it in GitHub Desktop.
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) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment