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?
Best way to use coroutine anywhere is to use the Structured Concurrency to manage all the lifecycle. GlobalScope does not implement the Structured Concurrency.
- 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){}
- 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?
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With