How to create periodic network request with RxJava only in foreground?

How should approach such problem: Suppose I need to create periodic network requests, which should only occur while app is in the foreground, because if they occur in the background network requests can terminate, with background service. I know that you would need this code for periodic requests:

  Observable.fromCallable(networkRequest())
          .repeatWhen(observable -> observable.delay(5, TimeUnit.SECONDS));

The problem is that, it will continue to be executed when app is in background…

I thought about adding LiveData somehow in order to unsubscribe from this in onStop and continue in onStart. However, I can’t find a correct approach to that.

If I would add all this to CompositeDisposable, it could terminate my network requests, if I would call disposable.clear() in onStop. So this is not correct solution, too.

i would also like to get solution for ViewModel, but if that is not possible to do in it, then activity would also suit as an observer.

@macsimus Can you please help with this when you get a chance? Thank you - much appreciated! :]

This topic was automatically closed after 166 days. New replies are no longer allowed.