Hi all :wave: what are your thoughts on having th...
# android-architecture
i
Hi all 👋 what are your thoughts on having the
ViewModel
be a
LifecycleObserver
so it can react to the view's lifecycle? There's some good arguments for each scenario: on one hand we don't want the
ViewModel
to "_know"_ about the view's lifecycle, however, it may also help make the
View
as dumb as possible and have more logic be done on the
ViewModel
.
h
I think it will completely depend on the use case. Can you share some more information about your use case.
👍 1
d
The view model should not need to know anything about view lifecycle. This is the best case scenario. If it really needs to (I have this usecase as well) best use a method on the view model to notify it of the lifecycle change. (I have for example a
onActivityPaused()
method there since I need to remove some things from the view when it goes into the background)
👍 1
h
I agree calling method improves code readability. Making viewModel as lifecycle observers and using annotations to call methods introduces too much magic in your code 😅
i
Well, the use case really is just to make an API call as soon as a fragment is created. Thought It'd be a good idea to just handle that from the
ViewModel
but I think I can avoid opening Pandora's box and just override the appropriate lifecycle function from the fragment and just call
ViewModel
from there. Thanks for the tips though!
d
Hmm, this sounds suspicous, can you explain what you want to do at fragment creation? Seen a lot of usecases like this that could be avoided by putting the logic elsewhere
i
Yeah it's sorta trivial really, just gotta make an API call as soon as we navigate to a screen. Which in our case we have the single activity approach and every screen is a fragment. I can always put the logic in the ViewModel's
init { ... }
function though.
d
That should be the best case. One view model for each fragment and the api call in the init. Otherwise you are doing the api call on every rotatio / recreation
👍 1