なぜか長ったらしくなる Observable のネスト.
Observable.just("yo")
.flatMap(s -> Observable.range(0, 100))
.subscribe(integer -> Ln.d("Here's an Integer(%s), but how do I access that juicy String?", integer));
よくあるくせに綺麗に書けない.
そんなわたし乙.
lambda も絡めてゆっくりと眺める.
元.
Observable.just("yo")
.flatMap(new Func1<String, Observable<? extends Integer>>() {
@Override public Observable<? extends Integer> call(String s) {
return Observable.range(0, 100);
}
})
.map(new Func1<Integer, String>() {
@Override public String call(Integer integer) {
return String.format("Here's an Integer(%s), but how do I access that juicy String?", integer);
}
})
.subscribe(new Action1<String>() {
@Override public void call(String x) {
System.out.println(x);
}
});
flatMap(Func1, Func2) でやる場合.
Observable.just("yo")
.flatMap(new Func1<String, Observable<? extends Integer>>() {
@Override public Observable<? extends Integer> call(String s) {
return Observable.range(0, 100);
}
}, new Func2<String, Integer, String>() {
@Override public String call(String s, Integer integer) {
return String.format("Here's an Integer(%s), with String(%s)", integer, s);
}
})
.subscribe(new Action1<String>() {
@Override public void call(String x) {
System.out.println(x);
}
});
flatmap に map を入れ子でやる場合.
Observable.just("yo")
.flatMap(new Func1<String, Observable<? extends String>>() {
@Override public Observable<? extends String> call(String s) {
return Observable.range(0, 100)
.map(new Func1<Integer, String>() {
@Override public String call(Integer integer) {
return String.format("Here's an Integer(%s), with String(%s)", integer, s);
}
});
}
})
.subscribe(new Action1<String>() {
@Override public void call(String x) {
System.out.println(x);
}
});
}
lambda へ
元.
Observable.just("yo")
.flatMap(s -> Observable.range(0, 100))
.map(integer -> String.format("Here's an Integer(%s), but how do I access that juicy String?", integer))
.subscribe(System.out::println);
flatMap(Func1, Func2) でやる場合.
Observable.just("yo")
.flatMap(s -> Observable.range(0, 100),
(s, integer) -> String.format("Here's an Integer(%s), with String(%s)", integer, s))
.subscribe(System.out::println);
flatmap に map を入れ子でやる場合.
Observable.just("yo")
.flatMap(s -> Observable.range(0, 100)
.map(integer -> String.format("Here's an Integer(%s), with String(%s)", integer, s)))
.subscribe(System.out::println);
まとめ
flatmap に map を入れるのがわかりやすいように思います.
慣れたらラムダも直感的です.
Feature request: @Passthru variable for Rx chains · Issue #855 · square/retrofit