Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava: how to complete observable from a different place?

Tags:

rx-java

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.

like image 723
Dariusz Mydlarz Avatar asked Nov 22 '25 05:11

Dariusz Mydlarz


1 Answers

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.

like image 132
Dave Moten Avatar answered Nov 24 '25 23:11

Dave Moten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!