Reputation: 1760
Short story: I have a situation where I have 2 Observables that have a single purpose:
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:
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().
How can I have this behaviour without running both operations twice?
Upvotes: 2
Views: 287
Reputation: 70007
This is not possible with Single
in 1.x because there is no notion of a ConnectableSingle
and thus Single.publish
. You can achieve the effect via 2.x and the RxJava2Extensions library:
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);
Upvotes: 2