概述
- flatMap将一个发送事件的上游Observable变换为多个发送事件的Observables,然后将它们发射的事件合并后放进一个单独的Observable里.
- flatMap并不保证事件的顺序,如果要保证事件的顺序,使用concatMap.
代码
public class Demo {
public static void main(String[] args) {
log("hello");
Observable.just(1, 2, 3).map(new Function<Integer, String>() {
@Override
public String apply(Integer integer) throws Exception {
return "" + integer;
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
log(s);
}
});
Observable.just(1, 2, 3).flatMap(new Function<Integer, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(Integer integer) throws Exception {
final List<String> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add("I am value " + integer + ", i = " + i);
}
return Observable.fromIterable(list);
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
log(s);
}
});
}
private static void log(String s) {
System.out.println(s);
}
}
运行结果:
hello
1
2
3
I am value 1, i = 0
I am value 1, i = 1
I am value 1, i = 2
I am value 2, i = 0
I am value 2, i = 1
I am value 2, i = 2
I am value 3, i = 0
I am value 3, i = 1
I am value 3, i = 2
flatMap接受的参数Function对象中,实现的apply方法的返回类型为ObservableSource,ObservableSource是一个接口,里面只有一个需要实现的方法subscribe,Observable类就实现了该接口,所以apply方法中返回Observable对象即可,这里通过Observable.fromIterable生成Observable对象。
public interface ObservableSource<T> {
/**
* Subscribes the given Observer to this ObservableSource instance.
* @param observer the Observer, not null
* @throws NullPointerException if {@code observer} is null
*/
void subscribe(@NonNull Observer<? super T> observer);
}