Created
October 23, 2019 15:35
-
-
Save LouisCAD/7690950f3a839730d025ca127b46ebde to your computer and use it in GitHub Desktop.
Convert a Flow to a LiveData and use LiveData as a Flow (from kotlinx.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
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.Observer | |
import androidx.lifecycle.liveData | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.flow.* | |
import kotlin.time.Duration | |
import kotlin.time.ExperimentalTime | |
import kotlin.time.seconds | |
@ExperimentalTime | |
fun <T> Flow<T>.toLiveData( | |
timeout: Duration = 5.seconds | |
): LiveData<T> = liveData(timeoutInMs = timeout.toLongMilliseconds()) { | |
collect { emit(it) } | |
} | |
@UseExperimental(ExperimentalCoroutinesApi::class) | |
fun <T> LiveData<T>.asFlow(): Flow<T> = callbackFlow { | |
val observer = Observer<T> { value -> offer(value) } | |
observeForever(observer) | |
awaitClose { | |
removeObserver(observer) | |
} | |
}.flowOn(Dispatchers.Main.immediate) |
I think it's actually included out of the box now and that this gist is no longer necessary.
Yup, actually yes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just as a note, you need the AndroidX LiveData dependency for this to work: