user982687
user982687

Reputation: 335

Coroutine Scoping with Fragment

I have a network call that gets some LiveData. The LiveData is observed with my Fragment's lifecycle owner so UI updates are safe. But does the coroutine call I make also need to be scoped to the fragment's lifecycleowner? In other words, does it matter which one of these I use?

CoroutineScope(Dispatchers.IO).launch

or

fragment.lifecycleScope.launch(context = Dispatchers.IO)

Upvotes: 5

Views: 6609

Answers (1)

Son Huynh
Son Huynh

Reputation: 939

CoroutineScope(Dispatchers.IO).launch{} is a CoroutineScope that launches all coroutines in it and return a Coroutine Job. But you need to call cancel() to stop all lauched coroutines in this scope if your activity/fragment/viewmodel is destroyed. If any coroutine keep running in background after that, it may leads to memory leaks.

fragment.lifecycleScope.launch(context = Dispatchers.IO){} is a Lifecycle-aware Coroutine Scope so any coroutine launched in this scope is automatically canceled if lifecycle (activity/fragment/viewmodel) is destroyed.

It's better to use coroutines with lifecycleScope so you don't have to manage the lifecycle of a Coroutine Job

Upvotes: 9

Related Questions