catalinghita8 / android-compose-mvvm-foodies

Android sample app following best practices: Kotlin, Compose, Coroutines and Flow, Hilt, JetPack Navigation, ViewModel, MVVM, Retrofit, Coil
476 stars 89 forks source link

[Question] Why is the loading state not displayed after a delay? #8

Closed JustJerem closed 3 years ago

JustJerem commented 3 years ago
 private suspend fun getFoodCategories() {
        setState { setIsLoading(true) }
        val categories = repository.getFoodCategories()
        setState {
            copy(categories = categories).setIsLoading(false)
        }
        **delay(2_000)**
        **setState { setIsLoading(true) }**
        setEffect { FoodCategoriesContract.Effect.DataWasLoaded }
    }

I'm trying to change the state information but this doesn't work if a delay is applied.

    delay(2_000)
    setState { setIsLoading(true) }

But the effect is well applied for this line.

        setEffect { FoodCategoriesContract.Effect.DataWasLoaded }

Do we know why ?

All in all, good job for this architecture.

catalinghita8 commented 3 years ago

First, thank you for your feedback. Secondly, this is a great catch. I investigated and there are actually 2 issues causing the loading bar to not appear anymore:

  1. The layout is broken for the FoodCategoriesScreen in the sense that the loading bar can never appear on top of the list if it's populated. This can be fixed by replacing the parent Surface with a Box to allow overlay behaviour.
  2. The state is being published through the compose runtime MutableState. If you define a state as a data class (in our case the FoodCategoriesContract.State) and inherit a field i.e. isLoading from an abstract class ViewState, any changes on the fields that are inherited from the ViewState abstraction will not make the UI recompose.

This is something I didn't expect and I'm not really sure why Compose is behaving this way. To fix it, I removed the abstract isLoading field and added it manually to the FoodCategoriesContract.State. At this moment, this is the only fix I could find.

The issues are addressed in this PR which I will merge soon. If you want to test your above behavior, check out the just-jerem-delay-test.

JustJerem commented 3 years ago

Thank you for testing.

  1. Is something like this not possible in the end?

     if (state.isLoading)
                LoadingBar()
    else
            FoodCategoriesList(...)
  2. And yes, while doing my tests, I came to the same conclusion that Compose did not recompose itself in the case of a legacy. It's a waste, let's see how it evolves because it's a good approach.

Thanks again ;)

catalinghita8 commented 3 years ago
  1. Yes you can use that. The issue with that approach is that if you toggle the loading, the content (the list) will not be visible again until you hide the loading again.
  2. Since the PR is merged, I will close this issue. Thanks again!