map变换操作符:将发送的数据按指定的函数去变化
例子:
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
e.onNext("1");
e.onNext("2");
e.onComplete();
}
}).map(new Function<String, Integer>() {
@Override
public Integer apply(String s) throws Exception {
//将String转换为Integer
return Integer.parseInt(s);
}
}).subscribe(new Consumer<Integer>() {
//此处泛型也应变为Integer
@Override
public void accept(Integer s) throws Exception {
}
});
flatMap变换操作符:将发送的事件分解成多个事件后发送回接收方
注意:flatMap并不保证事件的顺序,如需保证时间顺序使用concatMap
,使用方法和flatmap一样。
例子:
Observable.create(new ObservableOnSubscribe<User>() {
@Override
public void subscribe(ObservableEmitter<User> e) throws Exception {
//User 有id 和 name 两个属性
User user = new User();
user.setId(1);
user.setName("dog");
e.onNext(user);
User user1 = new User();
user1.setId(2);
user1.setName("cat");
e.onNext(user1);
e.onComplete();
}
}).flatMap(new Function<User, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(User user) throws Exception {
List<String> list = new ArrayList<>();
list.add(user.getId() + "");
list.add(user.getName());
return Observable.fromIterable(list);
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.d(TAG, "accept: " + s);
}
});
结果:
zip:类似于flatMap的逆过程,将多个事件合为一个事件。
例子:
Observable observable1 = Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter e) throws Exception {
e.onNext(1);
e.onNext(2);
}
});
Observable observable2 = Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter e) throws Exception {
e.onNext("dog");
e.onNext("cat");
}
});
Observable.zip(observable1, observable2, new BiFunction<Integer , String , User>() {
@Override
public User apply(Integer integer, String s) throws Exception {
User user = new User();
user.setId(integer);
user.setName(s);
return user;
}
}).subscribe(new Consumer<User>(){
@Override
public void accept(User user) throws Exception {
Log.e(TAG, "accept: " + user.toString() );
}
});
结果:
发现observable1发送完成后,observable才开始发送,因为两个发送方在同一线程中,可各自调用subscribeOn方法,让其运行在不同线程上。