Skip to content

Instantly share code, notes, and snippets.

@watabee
Created December 22, 2019 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watabee/ffb26d01e97ee4cb77f0936539d5b691 to your computer and use it in GitHub Desktop.
Save watabee/ffb26d01e97ee4cb77f0936539d5b691 to your computer and use it in GitHub Desktop.
Get value safely from LiveData for testing using kotlin coroutines
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.coroutines.resume
suspend fun <T : Any> LiveData<T>.awaitValue(): T? = withTimeoutOrNull(2000L) {
suspendCancellableCoroutine<T> { cont ->
val observer = object : Observer<T> {
override fun onChanged(t: T) {
this@awaitValue.removeObserver(this)
cont.resume(t)
}
}
this@awaitValue.observeForever(observer)
}
}
@kururu-abdo
Copy link

how to get single todo from Room database using coroutines

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