[英]RxJava combining observables without repeating execution
Short story: I have a situation where I have 2 Observables that have a single purpose:短篇故事:我有一种情况,我有 2 个具有单一目的的 Observable:
They are each in charge of handling different types of data.他们各自负责处理不同类型的数据。 Additionally I want to do something when both data has been processed.另外,我想在处理完两个数据后做一些事情。
My current best implementation is as follows, these are my Observables:我目前最好的实现如下,这些是我的 Observables:
Single<BlueData> blueObservable = Single.create(singleSubscriber -> {
if (BlueDataProcessor.isDataValid(myBlueData)) {
singleSubscriber.onSuccess(BlueDataProcessor.process(myBlueData));
}
else {
singleSubscriber.onError(new BlueDataIsInvalidThrow());
}
});
Single<RedData> redObservable = Single.create(singleSubscriber -> {
if (RedDataProcessor.isDataValid(myRedData)) {
singleSubscriber.onSuccess(RedDataProcessor.process(myRedData));
}
else {
singleSubscriber.onError(new RedDataIsInvalidThrowable());
}
});
Single<PurpleData> composedSingle = Single.zip(blueObservable, redObservable,
(blueData, redData) -> PurpleGenerator.combine(blueData, redData));
I also have the following subscriptions:我还有以下订阅:
blueObservable.subscribe(
result -> {
saveBlueProcessStats(result);
},
throwable -> {
logError(throwable);
});
redObservable.subscribe(
result -> {
saveRedProcessStats(result);
},
throwable -> {
logError(throwable);
});
composedSingle.subscribe(
combinedResult -> {
savePurpleProcessStats(combinedResult)
},
throwable -> {
logError(throwable);
});
MY PROBLEM: The blue & red data is processed twice, because both subscriptions are run again with I subscribe to the combined observable created with Observable.zip().我的问题:蓝色和红色数据被处理两次,因为两个订阅都再次运行,我订阅了使用 Observable.zip() 创建的组合 observable。
How can I have this behaviour without running both operations twice?如何在不运行两次操作的情况下获得这种行为?
This is not possible with Single
in 1.x because there is no notion of a ConnectableSingle
and thus Single.publish
.这在 1.x 中的Single
中是不可能的,因为没有ConnectableSingle
概念,因此没有Single.publish
。 You can achieve the effect via 2.x and the RxJava2Extensions library:可以通过 2.x 和 RxJava2Extensions 库实现效果:
SingleSubject<RedType> red = SingleSubject.create();
SingleSubject<BlueType> blue = SingleSubject.create();
// subscribe interested parties
red.subscribe(...);
blue.subscribe(...);
Single.zip(red, blue, (r, b) -> ...).subscribe(...);
// connect()
blueObservable.subscribe(blue);
redObservable.subscribe(red);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.