##map
http://reactivex.io/documentation/operators/map.html#collapseRxGroovy
output: T
從圖中可以看到
依序由Observable圈圈執行action後return T再變為Observable菱形輸出
numbers = Observable.from([1, 2, 3, 4, 5]);
numbers.map({it * it}).subscribe(
{ println(it); }, // onNext
{ println("Error: " + it.getMessage()); }, // onError
{ println("Sequence complete"); } // onCompleted
);
1
4
9
16
25
Sequence complete
##flatMap
http://reactivex.io/documentation/operators/flatmap.html#collapseRxGroovy
output: unordered Observables
從圖中可以看到
Observables全部攤平一齊輸入執行action後return Observables
可以從一個Observable圈圈變為多個Observables菱形輸出且是沒有順序的
例如此圖一個圈圈Observable變為兩個菱形Observables
而且綠色菱形2輸出較慢所以藍色菱形1會先輸出
但順序問題是因為action有執行Schedulers多執行序所導致
以下sample為一般單執行序所以會依序輸出結果
// this closure is an Observable that emits three numbers
numbers = Observable.from([1, 2, 3]);
// this closure is an Observable that emits two numbers based on what number it is passed
multiples = { n -> Observable.from([ n*2, n*3 ]) };
numbers.flatMap(multiples).subscribe(
{ println(it); }, // onNext
{ println("Error: " + it.getMessage()); }, // onError
{ println("Sequence complete"); } // onCompleted
);
2
3
4
6
6
9
Sequence complete
##concatMap
http://reactivex.io/documentation/operators/flatmap.html#collapseRxGroovy
output: ordered Observables
從圖中可以看到
跟flatMap是相似的
可以從一個Observable圈圈變為多個Observables菱形輸出但是是有順序的
例如此圖如果執行與flatMap同樣的action
綠色菱形2即使輸出較慢仍會先輸出後藍色菱形1才會輸出
就算action有執行Schedulers多執行序也會變為單執行序依序執行
RxJava Observable tranformation: concatMap() vs flatMap()
List<Integer> numbers;
Executor jobExecutor;
DataManager() {
this.numbers = new ArrayList<>(Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10));
this.jobExecutor = JobExecutor.getInstance();
}
Observable<Integer> squareOfAsync(int number) {
return Observable.just(number * number).subscribeOn(Schedulers.from(this.jobExecutor));
}
dataManager.numbers().flatMap(dataManager::squareOfAsync)
dataManager.numbers().concatMap(dataManager::squareOfAsync)
比較結果如下
##.Net
如果是.Net陣營對於命名感到困惑的話
可以參考每個Operator裡的See Also
Introduction to Rx: xxx
譬如
Map -> Select (Introduction to Rx: Select)
FlatMap -> SelectMany (Introduction to Rx: SelectMany)
另外ToList Operator
與.Net ToList截然不同
Rx是回傳一個Observable物件
http://reactivex.io/documentation/operators/to.html
但.Net則是回傳可列舉內容的多個物件