7

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?

Chirag Bhuva
  • 851
  • 7
  • 14

1 Answers1

6

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.

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
  • 1
    You don't need to create your own scope, there's already a [`lifecycleScope`](https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope) you can use. – ianhanniballake Apr 25 '20 at 05:13
  • 1
    those are part of `lifecycle-runtime-ktx`, nothing related to fragments – ianhanniballake Apr 25 '20 at 05:56
  • Thanks, ianhanniballake and @AnimeshSahu – Chirag Bhuva May 01 '20 at 03:47
  • @ianhanniballake Is it good to use lifecycleScope.launch{} in Activity or Fragment for making api calls which automatically manages lifecycles? – Sumit Shukla Jul 04 '20 at 07:02
  • @SumitShukla yes, as long as your API uses coroutines, it should change context when required, and at the end you'll be able to change the UI elements because lifecycleScope uses `Dispatchers.Main` :) – Animesh Sahu Jul 04 '20 at 07:12
  • `java.lang.IllegalStateException: Fragment not attached to an activity` In such case we must use viewLifecycleOwner.lifecycle scope will make sure the job is destroyed `onDestroyView` and does not survive the entire lifetime of the fragment. @ianhanniballake – Sai Feb 03 '21 at 14:08