Skip to content

Instantly share code, notes, and snippets.

Created February 1, 2018 03:59
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jamiesanson/a07c04976112dc4ea62f198dbf994939 to your computer and use it in GitHub Desktop.
LiveData NonNull Observers
* Extends LiveData allowing Kotlin DSL for onChanged callback usage
fun <T> LiveData<T>.observeNonNull(lifecycleOwner: LifecycleOwner, onItem: (T) -> Unit) {
this.observe(lifecycleOwner, object : NonNullObserver<T> {
override fun onChangedNonNull(t: T) {
* Interface of our new observer, using default functions
interface NonNullObserver<T>: Observer<T> {
override fun onChanged(t: T?) {
if (t != null) onChangedNonNull(t)
fun onChangedNonNull(t: T)
class TestActivity: AppCompatActivity() {
val liveData: LiveData<String> = MutableLiveData<String>()
override fun onCreate(savedInstanceState: Bundle?) {
// Observe the LiveData with our new extension
liveData.observeNonNull(this) {
Log.d("TestActivity", "Got: $it")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment