https://kotlinlang.org logo
Title
s

Saket Poddar

02/17/2020, 9:02 AM
Hi All, it might seem trivial, but I wanted to ask, shall cancel CoroutineScope in ViewModel$onCleared or shall I cancel in Activity$onDestroy. What is recommended???
d

dekans

02/17/2020, 9:10 AM
ViewModel scope must be cancelled in
onCleared()
Activity/Fragment scope must be in
onDestroyed()
But with AndroidX, ktx extensions you have
viewmodelScope
and
lifecycleScope
which are automatically instanciated and cancelled
s

Saket Poddar

02/17/2020, 9:16 AM
But if activity is tied to viewmodel then whats the issue in cancelling scope in viewmodel oncleared. Considering the case where screen orientation changes, coroutines called in CoroutineScope will be cancelled if I call in Activity$onDestroy
d

dekans

02/17/2020, 4:06 PM
Coroutines launched from ViewModel won't care about Activity recreation
s

Saket Poddar

02/18/2020, 7:51 AM
Thanks, I got the picture why corotuineScope launched from viewmodel should be cancelled on onCleared.