How to stop an observable upon click in RxAndroid?

535 Views Asked by At

I'm learning RxAndroid/RxBinding. I'm trying to stop an observable sequence upon a button click event but don't know how to do it.

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
Button bt = (Button)findViewById(R.id.button);

RxView.clicks(fab).subscribe(view ->Snackbar.make(SnakebarLayout, "Actions", Snackbar.LENGTH_LONG).setAction("Action", null).show());
RxView.clicks(bt).subscribe(view -> Observable.range(10, 5).subscribe(i-> Toast.makeText(this,i.toString(),Toast.LENGTH_SHORT).show()));

As you can see that I have two buttons each subscribed to an observable sequence, what I want is:

(1) If I click a button first then click the other button later, the observable actions from first button should stop immediately.

(2) If I click a button, then click it again, the observable should restart immediately . At the moment if I click it again, it will wait until the current observable finish then start again.

1

There are 1 best solutions below

0
On

First those code are not so good:

RxView.clicks(bt).subscribe(view -> Observable.range(10, 5).subscribe(i-> Toast.makeText(this,i.toString(),Toast.LENGTH_SHORT).show()));

change it into

RxView.click(bt)
      .flatMap(ignore -> Observable.range(10,5))
      .subscriber(//your toast)

As for your questions

(1) If I click a button first then click the other button later, the observable actions from first button should stop immediately.

Your subscribe() method will return you a disposable() which is a switch to let you control the stream.

you could just call disposable.dispose() inside your second button's subscribe().

(2) If I click a button, then click it again, the observable should restart immediately . At the moment if I click it again, it will wait until the current observable finish then start again.

this request a bit bizarre for me. So the first part will you can use switchMap instead of flatMap. The second part I don't quiet understand.