Created
February 1, 2018 03:59
-
-
Save jamiesanson/a07c04976112dc4ea62f198dbf994939 to your computer and use it in GitHub Desktop.
LiveData NonNull Observers
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
/** | |
* 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) { | |
onItem(t) | |
} | |
}) | |
} |
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
/** | |
* 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) | |
} |
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
class TestActivity: AppCompatActivity() { | |
val liveData: LiveData<String> = MutableLiveData<String>() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
// 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