FlatMap
transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.
This method is useful, for example, when you have an Observable that emits a series of items that themselves have Observable members or are in other ways transformable into Observables, so that you can create a new Observable that emits the complete collection of items emitted by the sub-Observables of these items.
Note that FlatMap merges the emissions of these Observables, so that they may interleave.
In several of the language-specific implementations there is also an operator that does not interleave the emissions from the transformed Observables, but instead emits these emissions in strict order, often called ConcatMap or something similar.
-----------------------------------------------------------------------------
List<String> list = new ArrayList<>();
list.add("List-1");
list.add("List-2");
list.add("List-3");
list.add("List-4");
list.add("List-5");
final TestScheduler scheduler = new TestScheduler();
Observable.fromIterable(list)
.flatMap( s -> {
final int delay = new Random().nextInt(10);
return Observable.just(s + "x")
.delay(delay, TimeUnit.SECONDS, scheduler);
})
.toList()
.subscribe(System.out::println);
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
----------------------------------------------------------------------------
FlatmapMaybe
-----------------------------------------------------------------------------
Observable.range(1, 10)
.flatMapMaybe(new Function<Integer, MaybeSource<?>>() {
@Override
public MaybeSource<?> apply(Integer integer) throws Exception {
return Maybe.just(integer);
}
})
.subscribe(System.out::println);
-----------------------------------------------------------------------------
Observable.range(1, 10)
.flatMapMaybe(new Function<Integer, MaybeSource<?>>() {
@Override
public MaybeSource<?> apply(Integer integer) throws Exception {
return Maybe.just(integer);
}
})
.subscribe(System.out::println);
-----------------------------------------------------------------------------
22
No comments:
Post a Comment