Skip to content

Instantly share code, notes, and snippets.

@tsun424
Forked from JoseAlcerreca/LiveDataTestUtil.java
Created August 31, 2021 10:55
Show Gist options
  • Save tsun424/31b74809809243b13c2bf78551a069a4 to your computer and use it in GitHub Desktop.
Save tsun424/31b74809809243b13c2bf78551a069a4 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];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment