Last active
September 21, 2024 11:21
-
-
Save JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba to your computer and use it in GitHub Desktop.
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
/* 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]; | |
} | |
} |
Thanks
Thanks:+1:
Thanks
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
Awesome! It works! Very useful, million thanks