-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
SingleFeatures.java
75 lines (62 loc) · 2.71 KB
/
SingleFeatures.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
75
package rx.single;
import org.junit.Test;
import rx.Observable;
import rx.Single;
import rx.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Pablo Perez
* Single is just another variant of observable as relay. In this particular case Single only emit one item.
* Since only emit 1 item in the pipeline, single only accept two Action functions, onSuccess and onError.
*/
public class SingleFeatures {
/**
* Here we can see constantClass basic example where Single just emit the item and onSuccess and onError functions are defined.
*/
@Test
public void testSingle() {
Single.just("Single").subscribe(result -> System.out.println("Result: " + result),
(error) -> System.out.println("Something went wrong" + error.getMessage()));
}
/**
* The fact that Single only emit 1 item does not means that cannot use all the ReactiveX features as zip, merge, concat, and so on.
* Here we use Zip to run two singles, which every one of those it will emit just 1 item.
*/
@Test
public void testZipSingles() {
Single<Integer> single = Single.just(1);
Single<Integer> single2 = Single.just(2);
Single.zip(single, single2, (s1, s2) -> s1 + s2)
.subscribe(result -> System.out.println("Result: " + result),
(error) -> System.out.println("Something went wrong" + error.getMessage()));
}
/**
* Also it´ possible use Single asynchronously using subscribeOn or observerOn
*/
@Test
public void testSinglesAsync() {
System.out.println("Current thread:" + Thread.currentThread()
.getName());
Single.just("Single").subscribeOn(Schedulers.newThread())
.subscribe(result -> System.out.println("Async Result in thread: " + Thread.currentThread()
.getName()),
(error) -> System.out.println("Something went wrong" + error.getMessage()));
}
/**
* flatMapObservable operator merge all items from constantClass list from Single into n observable of the list type
*/
@Test
public void flatMapObservable() {
Observable.just(Collections.singletonList(1))
.flatMap(word -> getObservables()
.flatMapObservable(Observable::from))
.collect(ArrayList<String>::new, List::add)
.subscribe(System.out::println, System.out::println, System.out::println);
}
private Single<List<String>> getObservables() {
return Single.just(Arrays.<String>asList("Hello", " flatMapObservable", " operator"));
}
}