Call ViewModel's fetch function with loading in Jetpack Compose called only once

Viewed 590

I have a problem with coping simple flow in Jetpack Compose. The scenario is simple:

  1. call Composable which draws screen and in its body call viewHolder's fetch method.
  2. viewHolder's fetch method first post isLoading.postValue(true)
  3. Composable shows loading animation
  4. viewHolder calls repository to fetch data and
  5. when receives it, sets isLoading.postValue(false) and posts fetched data
  6. Composable shows fetched data

My problem is with constant reloading composable and calls to viewHolder's calls to fetch data. How can I prevent that?

1 Answers

You should not cause side effects or change the state directly from the composable builder.

Instead you can use side effects.

In your case, LaunchedEffect must be used. Also, it is already running on the coroutines scope, so you can safely call the suspend functions.

LaunchedEffect(Unit) {
    viewHolder.fetch()
}

But even this is not totally "safe". In case of screen rotation LaunchedEffect will be relaunched too. I believe the only correct way is using a view model specific for a screen, and call fetch inside init.

Related