Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

How do I inherit from an Observable<T>?

I want to build an event broker class that inherits from Observable<EventArgs>. In the .NET implementation of Rx, you can simply implement IObservable<EventArgs>; furthermore, in .NET the publish() method just takes the argument that you want the subscribers to receive.

Can someone explain how this is done in Java? All I want is a class who inherently behaves as Observable<Foo>.

Upvotes: 3

Views: 837

Answers (1)

Oknesif
Oknesif

Reputation: 526

In most cases, there is no necessity to implement your own Observable inheritor. There is a bunch of fabrics methods to create Observable and handle it's behavior. For example:

Observable.create(new ObservableOnSubscribe<String>() {
    @Override public void subscribe(ObservableEmitter<String> emitter) throws Exception {
        emitter.onNext("New event");

        emitter.onError(new Error());

        emitter.onComplete();
    }
});

But, if you really need to create exactly an inheritor it is not difficult either.

class MarkedObservable extends Observable<String> {

    @Override protected void subscribeActual(Observer<? super String> observer) {
        observer.onNext("Message");

        observer.onError(new Error());

        observer.onComplete();
    }
}

Upvotes: 5

Related Questions