我有一个不那么漂亮的RxJava流程:-(
)RxView.clicks(sendButton)
.flatMap(ignored -> cameraManager.getCamera())
.flatMap(camera -> camera.isReachable())
.filter(reachable -> reachable)
.flatMap(ignored -> cameraManager.getCamera())
.flatMap(camera -> camera.sendCommand("foo bar"))
.subscribe(send -> Timber.i("send successful"),
error -> Timber.e(error, "send failed: "));
我不喜欢这群cameraManager.getCamera()
用相机做点什么。
是否有一种方法可以使flatMap
同时返回项目和其转换的结果,如flatMap(camera -> Pair.create(camera, camera.isReachable()))
?
RxView.clicks(sendButton)
.flatMap(ignored -> cameraManager.getCamera())
.flatMap(camera -> Pair.create(camera, camera.isReachable()))
.filter(pair -> pair.second)
.flatMap(pair -> pair.first.sendCommand("foo bar"))
.subscribe(send -> Timber.i("send successful"),
error -> Timber.e(error, "send failed: "));
更多代码来理解我的代码片段:
private class Bar {
private CameraManager cameraManager = new CameraManager();
private View sendButton = null;
public Bar() {
bind();
}
private void bind() {
RxView.clicks(sendButton)
.flatMap(ignored -> cameraManager.getCamera())
.flatMap(camera -> camera.isReachable())
.filter(reachable -> reachable)
.flatMap(ignored -> cameraManager.getCamera())
.flatMap(camera -> camera.sendCommand("foo bar"))
.subscribe(send -> Timber.i("send successful"),
error -> Timber.e(error, "send failed: "));
}
}
private class CameraManager {
public Observable<Camera> getCamera() {
return Observable.just(new Camera());
}
}
public class Camera {
private BehaviorSubject<Boolean> reachable = BehaviorSubject.create(false);
public Observable<Boolean> isReachable() {
return reachable.asObservable();
}
public Observable<Boolean> sendCommand(String msg) {
return Observable.create(subscriber -> {
// send message...
final boolean sendSuccessful = true;
if (sendSuccessful) {
subscriber.onNext(true);
subscriber.onCompleted();
} else {
subscriber.onError(new Exception());
}
});
}
}
有一个flatMap
过载,它有一个额外的Func2<T, U, R>
,它接受原始元素和每个元素生成的Observable<U>
,并返回一个要发出的值。
Observable.range(1, 10)
.flatMap(v -> Observable.range(1, 2), (v, w) -> v + 100 * w)
.subscribe(System.out.println);