forked from politrons/reactive
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ObservableCreate.java
74 lines (59 loc) · 2.24 KB
/
ObservableCreate.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package rx.observables.creating;
import org.junit.Test;
import rx.Observable;
import java.util.Arrays;
/**
* @author Pablo Perez
*/
public class ObservableCreate {
/**
* With the create operator, we are able to specify the items emitted on next or on error,
* to the observer
*/
@Test
public void testCreateObservableNext() {
Observable.create(observer -> {
observer.onNext("Injected value on Next");
}).map(s -> ((String) s).toUpperCase())
.subscribe(System.out::println, System.out::println);
}
/**
* With the create operator, we are able to specify the items emitted on next or on error,
* to the observer
*/
@Test
public void testCreateObservableError() {
Observable.create(observer -> {
observer.onError(new NullPointerException("This is the final exception"));
})
.map(s -> ((String) s).toUpperCase())
.subscribe(System.out::println, System.out::println);
}
/**
* operator to be executed once we subscribe to the observable.
*/
@Test
public void doOnSubscribe() {
Observable.from(Arrays.asList(1, 2, 3, 4))
.doOnSubscribe(()-> System.out.println("We just subscribe!"))
.flatMap(number -> Observable.just(number)
.doOnNext(n -> System.out.println(String.format("Executed in thread:%s number %s",
Thread.currentThread().getName(), n))))
.subscribe();
}
@Test
public void returnObservableInCreate() {
Integer[] numbers = {0, 1, 2, 3, 4};
Observable.create(observer -> observer.onNext(totalReadNumbers(numbers)))
.subscribe(n -> System.out.println(n + " in thread " + Thread.currentThread().getName()),
System.out::println);
}
private Integer totalReadNumbers(Integer[] numbers) {
return Observable.from(numbers)
.buffer(3)
.map(l -> l.stream()
.reduce((x, y) -> x + y))
.doOnNext(n -> System.out.println("Buffer Thread:" + Thread.currentThread().getName()))
.toBlocking().first().get();
}
}