Last active
April 19, 2019 05:50
-
-
Save chibatching/9fdd23d0d41980980a1c1af2e1803e01 to your computer and use it in GitHub Desktop.
LiveData as Flow of Kotlin Coroutines
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>.asFlow() = flowViaChannel<T?> { | |
it.send(value) | |
val observer = Observer<T> { t -> it.offer(t) } | |
observeForever(observer) | |
it.invokeOnClose { | |
removeObserver(observer) | |
} | |
} | |
val text = MutableLiveData<String>() | |
fun main() { | |
launch(Dispatchers.Main) { | |
text.asFlow() | |
.filterNot { | |
it.isNullOrBlank() | |
} | |
.collect { | |
println(it) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment