Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best practice to use coroutine with fragment?

Description
I have TabLayout with multiple fragments. I want to save fragment data into Room DB on fragment change/swipe and display data to the user when it back to fragment.

Currently Using
Currently, I am using coroutine with GlobalScope.launch to save into a fragment and it is working fine.

Questions
1. What is the best practice to use a coroutine with fragments to save data to DB on fragment change?
2. It is good practice to use GlobalScope.launch on fragment change?
3. if GlobalScope.launch is not good to use then what we can use instead of it?

like image 868
Chirag Bhuva Avatar asked Apr 25 '20 04:04

Chirag Bhuva


Video Answer


1 Answers

Best way to use coroutine anywhere is to use the Structured Concurrency to manage all the lifecycle. GlobalScope does not implement the Structured Concurrency.

  1. What is the best practice to use a coroutine with fragments to save data to DB on fragment change?

You can use LifecycleScope provided by android.

Inside the fragment you can launch the coroutine with the viewLifecycleOwner.lifecycleScope.launch{} and if you need some operation that should not be cancelled then launch them using viewLifecycleOwner.lifecycleScope.launch(NonCancellable){}

  1. It is good practice to use GlobalScope.launch on fragment change?

No, GlobalScope is highly discouraged to be used: see more at Why not use GlobalScope.launch?

  1. if GlobalScope.launch is not good to use then what we can use instead of it?

You can use the lifeCycleScope as mentioned by @ianhanniballake.

like image 185
Animesh Sahu Avatar answered Oct 21 '22 15:10

Animesh Sahu