Mattia Dinosaur
Mattia Dinosaur

Reputation: 920

Some concept about Rxjava: Observer pattern, and event

I read some page and it define Rxjava is a library for composing asynchronous and event-based programs using observable sequences for the Java VM. And it is base on Observer pattern.

Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
    subscriber.onNext("Hello");
    subscriber.onNext("Hi");
    subscriber.onNext("Aloha");
    subscriber.onCompleted();
}

});

In my opinion , the observer pattern like the button and the listener of button .If you click the button ,the button will create a event to notify the listener to run .

the question is :

  1. is my undestanding of concept about button and listener right ?
  2. I find the article of code above says that it will run at once , can i notify the observer not at once . In this example , i want to send any string i input instead of this three string .

Upvotes: 0

Views: 503

Answers (1)

Dave Moten
Dave Moten

Reputation: 12087

Have a look at PublishSubject. It is both an observable source that you can subscribe to and you can send it events too. In terms of a UI button you could do this:

final PublishSubject<String> subject = PublishSubject.create();

final Observable<String> o = 
    subject.doOnNext(...)
           .doOnError(...)
           .subscribe();

in the button listener:

public void onEvent(Event event) {
    subject.onNext(event.name());
}

Upvotes: 2

Related Questions