Created
December 22, 2019 08:13
-
-
Save watabee/ffb26d01e97ee4cb77f0936539d5b691 to your computer and use it in GitHub Desktop.
Get value safely from LiveData for testing using 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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to get single todo from Room database using coroutines