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

Slackbot

10/26/2019, 4:07 AM
This message was deleted.
t

Tash

10/26/2019, 6:37 AM
Sounds like your
ViewModel
belongs to the
Activity
? Just one
ViewModel
could be fine especially if things are simple enough and the data flow is unidirectional going towards the independent `Fragment`s. For one of my projects, I define some data models to represent each of the different `Fragment`s I have, and then configure the
Activity
level
ViewModel
to provide separate `LiveData`s of each of those models. Each
Fragment
then observes only the
LiveData
that pertains to its own data model.
👍 1
m

Michael Pohl

10/26/2019, 3:48 PM
It strongly depends on what kind of data you need to observe and what states you need. I’d usually always go with a separate view model per fragment, because a) it makes the classes smaller and easier to understand and b) I am less likely to run into sideeffects by sharing a view model and accidentally changing another fragment’s view.
👍 1
f

Freedom

10/27/2019, 8:27 PM
In your case using the same viewmodel is great since it they observe the same livedata and it simple
👍 1
a

Amirul Zin

10/29/2019, 2:08 AM
Assuming everything is the same except maybe some parameters you can pass into, you can define a single ViewModel class but simply scope it separately per fragment. I believe the loading state of each Fragment is not closely tied to each other, hence scoping it with the parent activity might actually mix your states unless your ViewModel actually kept them in proper order as per what @Tash did.
👍 1
s

Somesh

10/30/2019, 4:49 AM
@Michael Pohl Yeah, Thanks for the suggestion and I agree with what you're saying but I my case I shared the same ViewModel because they call the same API and observes the same Response class.
@Tash I following the single activity architecture and tying this one screen
ViewModel
with the activity sounded little off initially so I tied them to fragment scope and yeah everything is same except the title of the tabs.. and if I tie them to activity then I might not be able to easily load/call the APIs separately with different request as @Amirul Zin stated.