2

I have a library module that is making network calls using retrofit2 and RxJava. Calls are made when the app starts and toast message is displayed when they succeed. After starting the app if I close the app using the back press before the result comes, toast is being displayed after some time, which means calls are running in the background. I don't want that. if I close the app network calls should be canceled. It's not happening if I remove the app from recent apps.

1 Answers1

0

You would need to do this:

1) Identify when app goes to background - this can be done at one place using ProcessLifecycleOwner class, see sample implementation

2) Once App goes to background, invoke cancel() or cancelAll() depending on whether you want to cancel one or all background API calls.

Since you want to cancel all operations when app is closed, the best approach i think is to use coroutine with ViewModel scope to invoke API operation. This way, as soon as your app is closed, ViewModel scope will go over and hence associated pending operation will be auto cancelled, clean and concise implementation ! Reference Hope this helps !

Birender Singh
  • 513
  • 6
  • 16