Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Last active March 17, 2023 08:16
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba to your computer and use it in GitHub Desktop.
/* Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
public class LiveDataTestUtil {
public static <T> T getOrAwaitValue(final LiveData<T> liveData) throws InterruptedException {
final Object[] data = new Object[1];
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> observer = new Observer<T>() {
@Override
public void onChanged(@Nullable T o) {
data[0] = o;
latch.countDown();
liveData.removeObserver(this);
}
};
liveData.observeForever(observer);
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(2, TimeUnit.SECONDS)) {
throw new RuntimeException("LiveData value was never set.");
}
//noinspection unchecked
return (T) data[0];
}
}
@dmtr-pimenov
Copy link

Awesome! It works! Very useful, million thanks

@Mohsents
Copy link

Thanks

@tsun424
Copy link

tsun424 commented Aug 31, 2021

Thanks:+1:

@mahmoudhamdyae
Copy link

Thanks

@dyarza88
Copy link

dyarza88 commented Dec 8, 2022

In case you get the Exception cannot invoke observeforever on a background thread you probably need to add this:

In your build.gradle (Module):

androidTestImplementation "androidx.arch.core:core-testing:2.1.0"

In your Test class

For Java:

@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

For Kotlin:

@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()

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