Skip to content

Instantly share code, notes, and snippets.

@Puneet1796
Created January 16, 2021 21:39
Show Gist options
  • Save Puneet1796/427108d303cb691e258c085c719ed134 to your computer and use it in GitHub Desktop.
Save Puneet1796/427108d303cb691e258c085c719ed134 to your computer and use it in GitHub Desktop.
// This is the Java equivalent function for GetLiveDataValue.kt gist.
// Refer to link below
// https://gist.github.com/Puneet1796/ac1803b96735c61cbe1a8c86f473681f
@SuppressWarnings("unchecked")
@Nullable
public static <T> T getBlockingValue(@NotNull final LiveData<T> liveData) throws InterruptedException {
final Object[] value = new Object[1];
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> innerObserver = new Observer<T>() {
@Override
public void onChanged(@Nullable T newValue) {
value[0] = newValue;
latch.countDown();
liveData.removeObserver(this);
}
};
liveData.observeForever(innerObserver);
latch.await(2, TimeUnit.SECONDS);
return (T) value[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment