Arik6
Arik6

Reputation: 123

How to repeat operation every 15 seconds in RXJava2 and how to start and stop it

I have a thread that makes HTTP operations, Updating the UI and repeats every 20 seconds.

I need to convert this java thread to RXJava2 (Android RX).

There is no need to run it when the app is in a sleeping mode (onPause) But when the user returns to the app (onResume) the observable needs to subscribe and run immediately (Emits Data) and then continue the 20 seconds repetition.

I managed to do the repeat action and cancel it in onPause, but I cannot perform the Subscribesion operation again in the onResume method - It's just stops.

Here is my code. Thank You.

 protected void onResume() {
super.onResume();
     disposables = MainCulc_Observable()
  .interval(0, 5, TimeUnit.SECONDS)
  .subscribeOn(Schedulers.io())   // Run on a background thread
  .observeOn(AndroidSchedulers.mainThread())     // Be notified on the main thread
  .subscribeWith(MainCulc_Observer);
 } 

   @Override
 protected void onPause() {
super.onPause();

 disposables.dispose();
}

  DisposableObserver MainCulc_Observer = new DisposableObserver<Long>() {

@Override
public void onError(Throwable e) {
}

@Override
public void onComplete() {
}

@Override
public void onNext(Long status) {
}
   };

Upvotes: 0

Views: 151

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

You can't reuse an Observer. Instead of

.subscribeWith(MainCulc_Observer);

do

.subscribeWith(new DisposableObserver<Long>() {

@Override
public void onError(Throwable e) {
}

@Override
public void onComplete() {
}

@Override
public void onNext(Long status) {
}
   };)

Upvotes: 2

Related Questions