-
-
Save tsun424/31b74809809243b13c2bf78551a069a4 to your computer and use it in GitHub Desktop.
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
/* 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