Skip to content

Instantly share code, notes, and snippets.

@tinmegali
Created July 14, 2017 19:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tinmegali/718dd734d58e00a14e0058491c856fc8 to your computer and use it in GitHub Desktop.
Save tinmegali/718dd734d58e00a14e0058491c856fc8 to your computer and use it in GitHub Desktop.
Kotlin extension to allow Unit tests on Android LiveData
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
}
@PauloHInocencio
Copy link

Cool

@jraska
Copy link

jraska commented Dec 9, 2018

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().

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