Skip to content

Instantly share code, notes, and snippets.

@LouisCAD
Created October 23, 2019 15:35
Show Gist options
  • Save LouisCAD/7690950f3a839730d025ca127b46ebde to your computer and use it in GitHub Desktop.
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).
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)
@ArnyminerZ
Copy link

Just as a note, you need the AndroidX LiveData dependency for this to work:

def lifecycle_version = "2.2.0"

// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"

@LouisCAD
Copy link
Author

I think it's actually included out of the box now and that this gist is no longer necessary.

@ArnyminerZ
Copy link

Yup, actually yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment