flatMap in RxJava basic introduction for Beginners
flatMap in RxJava basic introduction for Beginners
Observable.flatMap() takes the emissions of one Observable and returns the emissions of another Observable to take its place.
Here’s how it works:
query("Hello, world!")
.flatMap(new Func1<List<String>, Observable<String>>() {
@Override
public Observable<String> call(List<String> urls) {
return Observable.from(urls);
}
})
.subscribe(url -> System.out.println(url));
I’m showing the full function just so you can see exactly what happened, but simplified with lambdas it looks awesome:
query("Hello, world!")
.flatMap(urls -> Observable.from(urls))
.subscribe(url -> System.out.println(url));
Why is it returning another Observable
? The key concept here is that the new Observable
returned is what the Subscriber
sees. It doesn’t receive a List<String>
– it gets a series of individual Strings
as returned by Observable.from()
.
0 Comments