Hi Would you guys consider having a ViewModel inje...
# android
j
Hi Would you guys consider having a ViewModel injected into another one as a bad practice?
👌 18
🚫 1
not kotlin but kotlin colored 1
p
I would, I believe the original papers drafting the pattern indicate that a VM is made to be consumed by a View in a one to one relationship. One View type to one view model type. Anything outside of that pattern is something else. If VM1 depends on VM2 then extract common functionality to ServiceX and make VM1, VM2 depend on ServiceX
👍 2
c
if you want to re-use functionality from your viewmodel, extract it and inject it into both of the (or however many) viewmodels.
👍 1
s
I don't understand why it is considered as a bad practice. If extending a Viewmodel isn't a bad practice and acceptable, passing another Viewmodel should be also acceptable. There is no much difference between extending and passing it. Almost both create a tight coupling.
v
Coupling between a VM and BaseVM okay. Coupling between a VM of Feature 1 with VM of Feature 2 is not okay and not "almost" the same
2
s
What if the feature 2 is an extension of feature 1?
v
BaseFeatureViewModel Feature 1 : BaseFeatureViewModel Feature 2 : BaseFeatureViewModel
👍 1
If you like doing something like Create/Edit order features, which has quite a lot in common
👍 1
a
We can create a delegate in such scenarios to extract out the common code.
👍 1
c
as a general rule, keeping your inheritance hierarchies as small as possible is almost always favourable. A ViewModel in particular is a concept that dictates a strong coupling between the view model and the view that interacts with it. Having one view model delegate to another, although it would work, just conceptually makes little sense. It'd be enough for any developer familiar with the ideas behind view models to go "uh, why are we doing that?". The other thing to consider is, the behaviour is similar now, but in the future it may diverge a lot, but the divergence may occur over months or years, where by "ok we'll just add this one thing." will happen many times until you end up with this frankenstein monster-esque viewmodel that doesn't really accurately represent it's actual intention anymore. Composition over inheritance will hopefully reduce this kind of tech debt in the future, as it'll be easier to go "we should probably pass something else in instead now". YMMV though and it might be perfectly fine, but you'll be having conversations with every new dev who looks at it, I can almost guarantee 😂
❤️ 4
k
@Abhimanyu do you have an example of delegates ?
a
I don’t have an example to share for now.