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.
Asked
Active
Viewed 526 times
2
-
2Have you tried using `Call.cancel()` or HttpClient method `OkHttpClient.dispatcher().cancelAll()`? – ρяσѕρєя K Jan 08 '20 at 05:58
-
post your code so which object can be used to cancel can be identified. – Vir Rajpurohit Jan 08 '20 at 05:59
-
But where should I call it? I don't want these calls to be canceled when I switch the activity. @ρяσѕρєяK – Sanjay Prajapat Jan 08 '20 at 06:00
-
BTW it's a library module. – Sanjay Prajapat Jan 08 '20 at 06:01
-
@SanjayPrajapat: `I don't want these calls to be canceled when I switch the activity` in Activity onBackPressed – ρяσѕρєя K Jan 08 '20 at 06:07
1 Answers
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