-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
ObservableAmbConditional.java
57 lines (46 loc) · 1.7 KB
/
ObservableAmbConditional.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package rx.observables.utils;
import org.junit.Test;
import rx.Observable;
import rx.Subscription;
import java.io.Serializable;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @author Pablo Perez
*/
/**
* Amb conditional it will get the first observable that start emitting, and it will avoid the others
*/
public class ObservableAmbConditional {
/**
* Amb conditional only takes into account the first observable that start emitting, the second one will be avoided completely
*/
@Test
public void ambObservable() {
Observable<String> words = Observable.just("Some", "Other");
Observable<Long> interval = Observable
.interval(500L, TimeUnit.MILLISECONDS)
.take(2);
subscribePrint(Observable.amb(words, interval), "Amb 1");
}
/**
* In here it will depend which of the data source start before
*/
@Test
public void ambObservableRandom() {
Random r = new Random();
Observable<String> source1 = Observable
.just("data from source 1")
.delay(r.nextInt(1000), TimeUnit.MILLISECONDS);
Observable<String> source2 = Observable
.just("data from source 2")
.delay(r.nextInt(1000), TimeUnit.MILLISECONDS);
subscribePrint(Observable.amb(source1, source2), "Amb 2");
}
Subscription subscribePrint(Observable<Serializable> observable, String name) {
return observable.subscribe((v) -> System.out.println(name + " : " + v), (e) -> {
System.err.println("Error from " + name + ":");
System.err.println(e.getMessage());
}, () -> System.out.println(name + " ended!"));
}
}