RxAndroid button click Observer?

拟墨画扇 提交于 2019-12-03 21:37:33

Use RxBinding

Subscription s = RxView.clicks(button)
        .throttleFirst(5, TimeUnit.SECONDS) // maybe you want to ignore multiple clicks
        .flatMap(foo -> fetchWeatherInterval)
        .subscribe(displayWeatherInterval);

throttleFirst just stops further events for next 5 seconds so if user clicks the button multiple times, the same fetchWeatherInterval won't be triggered again, for the next 5 seconds, of course.

flatMap converts output of one observable into another observable, in this case from click event to fetchWeatherInterval. Read the docs if you need more info.

Also, RxJava2 works as well, I just answered this for RxJava1. Just change Subscription to Disposable.

Using Observable.create():

Observable.create(new Action1<Emitter<View>>() {
    @Override
    public void call(Emitter<View> emitter) {
        emitter.setCancellation(new Cancellable() {
            @Override
            public void cancel() throws Exception {
                button.setOnClickListener(null);
                emitter.onCompleted();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emitter.onNext(v);
            }
        });
    }
}, Emitter.BackpressureMode.DROP);

Or with lambda:

Observable.create(emitter -> {
    emitter.setCancellation(() -> {
        button.setOnClickListener(null);
        emitter.onCompleted();
    });
    button.setOnClickListener(emitter::onNext);
}, Emitter.BackpressureMode.DROP);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!