-
-
Save harryhan24/11f0bae057c19c0cca0f024765da7b67 to your computer and use it in GitHub Desktop.
LiveData NonNull Observers
This file contains hidden or 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 hidden or 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 hidden or 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