Hi guys, What approach do you use when you have a ...
# android
r
Hi guys, What approach do you use when you have a feature with several steps ? where these steps are fragments. Do you use a viewmodel for each fragment or a sharedViewModel for all fragments?
đŸ˜¶ 5
s
First of all, not kotlin. But that's not useful. I tend to avoid shared viewmodels in almost all cases, unless like all the code is going to end up duplicated I'd go with individual viewmodels for each fragment. Imo there should be a tight coupling between a fragment and it's viewmodel. They're two sides of the same koin (pun intended)
➕ 2
c
Not sure if it’s a great option, but you could potentially create an Object (singleton). Set each value when something changes in the Fragment and when going back to previous Fragment you could read out those values. đŸ€”
t
It depends on what is sharable and what is unsharable. You must define them carefully. For example, you have a view model for loading and storing basic info of all friend list (id, name) In fragment A, you display bookmarked friends; in fragment B, you display blocked friends. Basic info for all friends are shared but bookmarked and blocked are not. Simple structure: Activity: FriendListViewModel Fragment A: BookmarkViewModel Fragment B: BlockedViewModel On each View Model, you can use Flow or LiveData to store values, then using combine to have the final renderable items.
c
I like using a pattern of each each Fragment having it’s own VM, where each consume a StateFlow from the Activity’s VM. For any given screen, any of the “shared” data should be collected from the activity VM and copied into the Fragment’s VM, and the activity’s VM is never used or exposed directly to the UI. In this way, each screen is still effectively isolated and can be iterated independently of changes to the shared data, and the activity state is just another reactive data source it happens to be reading from.
r
Sorry for not kotlin and thank you for your approaches guys