-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiveDataTestUtil.java
More file actions
40 lines (32 loc) · 1.17 KB
/
Copy pathLiveDataTestUtil.java
File metadata and controls
40 lines (32 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.anikinkirill.unittesting.util;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class LiveDataTestUtil<T> {
public T getValue(final LiveData<T> liveData) throws InterruptedException {
final List<T> data = new ArrayList<>();
// latch for blocking thread until data is set
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> observer = new Observer<T>() {
@Override
public void onChanged(T t) {
data.add(t);
latch.countDown(); // release the latch
liveData.removeObserver(this);
}
};
liveData.observeForever(observer);
try {
latch.await(2, TimeUnit.SECONDS); // wait for onChanged to fire and set data
} catch (InterruptedException e) {
throw new InterruptedException("Latch failure");
}
if(data.size() > 0){
return data.get(0);
}
return null;
}
}