Group Group Group Group Group Group Group Group Group

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

#1

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.