0

I have viewmodel call TestViewModel and a method call fetchDataFromDataSource() to call fetch data from the server, I used to call load data on OnResume() until I bump into lifecycleScope

I have tried to read more but didn't really get which is better.

class TestViewModel: Viewmodel() {

    fun fetchDataFromDataSource(){
       ....
    }
}




class TestActivity : AppCompatActivity() {

private val viewModel: TestViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
    ...

    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
        // Is it best to call here 
         viewModel.fetchDataFromDataSource()
        }
    }
}

onResume(){
  super.onResume()
  // or is it best to call here 
         viewModel.fetchDataFromDataSource()
}

}

where is the best place to call fetchDataFromDataSource(), is it in onResume() or lifecycleScope and what is the advantage lifecycleScope has over onResume() or onStart()

I know the view has rendered at onResume() so what benefit does lifecycleScope has over android lifecycle (onResume onCreate onStart...)

Muraino
  • 554
  • 7
  • 18

1 Answers1

0

repeatOnLifecycle is similar to calling methods on the respective lifecycle events every time the Activity hits that state but with a quick access to the lifecycleScope which can launch a coroutine.

Example:

override fun onResume(){
    super.onResume()
    viewModel.fetchDataFromDataSource()
}

is equivalent to -

class MainActivity : AppCompatActivity {

  init {
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.RESUMED) {
           viewModel.fetchDataFromDataSource()
      }
    }
  }
}

If you want to load the data from ViewModel every time the user comes to foreground from background, use onStart or repeatOnLifecycle(Lifecycle.State.STARTED).

If you need to load the data everytime the Activity resumes, then use onResume or the lifecycleScope equivalent as shown above but if this is just a one-time op, consider using onCreate.

Darshan
  • 4,020
  • 2
  • 18
  • 49
  • Thanks, but I am really confuse on what problem lifecycleScope solved if I can call my function from onCreate() or onResume()... is there any advantages – Muraino Sep 12 '22 at 09:28
  • There's not much difference apart from that it is a `suspend` function & was primarily created to collect the `Flow`s safely with a restartable behaviour. You can still use your functions in relevant lifecycle methods like `onResume` or `onStart`. – Darshan Sep 12 '22 at 11:38