https://kotlinlang.org logo
#android
Title
# android
m

Marcin Wisniowski

05/07/2020, 5:04 PM
Hello, I'm trying to build a single activity app with the navigation library. My fragments load some data from the network in their `ViewModel`s. I want to show a loading screen when data is loading, without creating a loading screen in every fragment, so I want to have a loading screen layout in the main activity layout. But how do I communicate the loading state to the Activity? If the loading screen was in the Fragment, I could just have a
LiveData
with the loading state and toggle the loading screen based on that. But if the loading screen is in the Activity, I have no access to the Fragment's
ViewModel
. What am I missing?
f

Fatih

05/07/2020, 5:11 PM
Create a shared activity viewmodel and add a live data to store loading state. Every fragment hosted by activity can access the shared viewmodel.
m

Marcin Wisniowski

05/07/2020, 5:14 PM
I thought about that, but I cannot access the shared
ViewModel
from the Fragment's
ViewModel
. And the network request is happening in the
ViewModel
. So I would need to have a loading state
LiveData
in the Fragment's
ViewModel
, observe it in the fragment, only to relay it to the shared
ViewModel
. Is this the best I can do?
r

Remy Benza

05/17/2020, 9:43 AM
Why have 2 viewmodels for your fragment? Like @Fatih says just use 1 tied to the activity lifecycle with the convenient activityViewmodels {} extension function.
Let the network requests take place there and set a LiveData network state variable while fetching networkdata.
Your activity also has access to this viewmodel so it can observe this variable to show/hide your loading UI
m

Marcin Wisniowski

06/01/2020, 7:34 PM
@Remy Benza I have 25 screens/Fragments, some doing more than one network request. Each screen needs it's own ViewModel, I can't have one ViewModel for the entire app. I ended up having a loading state LiveData in each Fragment's ViewModel that needs one, then the Fragment observes the loading state and passes it on to the Activity's ViewModel, so the Activity can observe it and show/hide the loading/error screens. I was originally not happy with having the Fragments observe the loading state just to pass it on to another ViewModel, but it's just one line per Fragment so it's not a problem after all.
2 Views