How do I create in RxJava an object (future) that is completed from a different place, but I want to return an observable to some client?
class DeferredAction {
private final CompletableFuture<String> future;
private final Observable<String> observable;
public DeferredAction() {
future = new CompletableFuture<>();
observable = Observable.from(future);
}
public Observable<String> observe() {
return observable;
}
public void complete(Stirng value) {
future.complete(value);
}
}
Is that the correct way? Second question: how I can get multiple subscribers on that observable? At the moment I see that only one subscriber works.
That should work although you should be aware of PublishSubject which is both an Observable and an Observer so you can do this:
PublishSubject<String> subject = PublishSubject.create();
subject.take(10).subscribe(sub1);
subject.last().subscribe(sub2);
subject.onNext("boo");
subject.onCompleted();
As you can see, this pattern also supports multiple subscribers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With