Rxjava map和flatMap區別
阿新 • • 發佈:2019-01-01
map和flatMap都是依賴傳入的Function對資料進行變換
但是
1、返回值上面:
map變換後可以返回任意值,而flatMap則只能返回ObservableSource型別
2、變換後的輸出:
map只能進行一對一的變換,而flatMap則可以進行一對一,一對多,多對多的變換,具體的變換規則根據我們設定的變換函式mapper來定
demo
List<String> list = new ArrayList<>(); list.add("b"); list.add("a"); list.add("c"); System.out.println("1對1:[b, a, c]-->[b, a, c]"); //1對1 Observable.just(list) .flatMap( new Function<List<String>, ObservableSource<?>>() { @Override public ObservableSource<?> apply(List<String> s) throws Exception { // System.out.println("map--1----" + s); return Observable.fromArray(s); } }) .subscribe(s -> { System.out.println(s); }); System.out.println("1對多:[b, a, c]-->b, a, c"); //1對多 Observable.just(list) .flatMap( new Function<List<String>, ObservableSource<?>>() { @Override public ObservableSource<?> apply(List<String> s) throws Exception { // System.out.println("map--1----" + s); return Observable.fromIterable(s); } }) .subscribe(s -> { System.out.println(s); }); //1對多 System.out.println("多對多:a, b, c-->[a, c]"); Observable.just("a", "b", "c") .flatMap( new Function<String, ObservableSource<?>>() { @Override public ObservableSource<?> apply(String s) throws Exception { // System.out.println("map--1----" + s); if (s.equalsIgnoreCase("b")) return Observable.empty(); return Observable.just(s); } }) .subscribe(s -> { System.out.println(s); }); //1對多 System.out.println("多對多:a, b, c-->a,b,c,d"); Observable.just("a", "b", "c") .flatMap( new Function<String, ObservableSource<?>>() { @Override public ObservableSource<?> apply(String s) throws Exception { // System.out.println("map--1----" + s); if (s.equalsIgnoreCase("c")) return Observable.just("c", "d"); return Observable.just(s); } }) .subscribe(s -> { System.out.println(s); }); System.out.println("map 一對一:[b, a, c]-->[b, a, c]"); Observable.just(list) .map(new Function<List<String>, List<String>>() { @Override public List<String> apply(List<String> strings) throws Exception { return strings; } }) .subscribe(s -> { System.out.println(s); });
輸出:
1對1:[b, a, c]-->[b, a, c]
[b, a, c]
1對多:[b, a, c]-->b, a, c
b
a
c
多對多:a, b, c-->[a, c]
a
c
多對多:a, b, c-->a,b,c,d
a
b
c
d
map 一對一:[b, a, c]-->[b, a, c]
[b, a, c]