Created
July 14, 2017 19:14
-
-
Save tinmegali/718dd734d58e00a14e0058491c856fc8 to your computer and use it in GitHub Desktop.
Kotlin extension to allow Unit tests on Android LiveData
This file contains hidden or 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
package com.tinmegali.daggerwithkotlin.room | |
import android.arch.lifecycle.LiveData | |
import android.arch.lifecycle.Observer | |
import java.util.concurrent.CountDownLatch | |
import java.util.concurrent.TimeUnit | |
// Extension to allow unit tests on LiveData | |
// discussion on: https://stackoverflow.com/questions/44270688/unit-testing-room-and-livedata | |
fun <T> LiveData<T>.blockingObserve(): T? { | |
var value: T? = null | |
val latch = CountDownLatch(1) | |
val innerObserver = Observer<T> { | |
value = it | |
latch.countDown() | |
} | |
observeForever(innerObserver) | |
latch.await(2, TimeUnit.SECONDS) | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, looks nice!
I found similar code in Google I/O app so it looks like a way to go :) Also this library allows you to achieve the same by
liveData.test().awaitValue()
.