How to create an Observable from OnClick Event Android?

Thanh Le picture Thanh Le · Aug 23, 2014 · Viewed 31.3k times · Source

I'm new in reactive programming. So I have problem when create a stream from an Event, like onClick, ontouch...

Can anyone help me solve this problem.

Thanks.

Answer

Miguel Lavigne picture Miguel Lavigne · Aug 23, 2014

You would do something like this:

Observable<View> clickEventObservable = Observable.create(new Observable.OnSubscribe<View>() {
    @Override
    public void call(final Subscriber<? super View> subscriber) {
        viewIWantToMonitorForClickEvents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (subscriber.isUnsubscribed()) return;
                subscriber.onNext(v);
            }
        });
    }
});

// You can then apply all sorts of operation here
Subscription subscription = clickEventObservable.flatMap(/*  */);

// Unsubscribe when you're done with it
subscription.unsubscribe();

Since you're using Android then you may already include the contrib rxjava-android dependency now known as ioreactivex:rxandroid. They already have a class to facilitate this. The method is ViewObservable.clicks. You can use it like so.

Observable<View> buttonObservable = ViewObservable.clicks(initiateButton, false);
    buttonObservable.subscribe(new Action1<View>() {
        @Override
        public void call(View button) {
            // do what you need here
        }
    });

Edit: Since version 1.x, ViewObservable and many helper classes are removed from RxAndroid. You will need RxBinding library instead.

Observable<Void> buttonObservable = RxView.clicks(initiateButton);
    buttonObservable.subscribe(new Action1<Void>() {
        @Override
        public void call(Void x) {
            // do what you need here
        }
    });