Created
January 16, 2021 21:39
-
-
Save Puneet1796/427108d303cb691e258c085c719ed134 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
// 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