While using MVVM I have a lot of live data objects...
# android
k
While using MVVM I have a lot of live data objects inside ViewModel (especially for actions), so I made this: https://pastebin.com/DhXKEpAA What cons can it have? Combined with coroutines it can be like this: https://pastebin.com/6phjEQZC
a
something like moko-mvvm
EventsDispatcher
https://github.com/icerockdev/moko-mvvm#viewmodel-with-send-events-to-view good approach - interface much better than separated event classes for every action
r
If I understand correctly, you’ve got a view that implements
LoginAcceptable
. The post in the livedata is actually just a method call on that View. But what happens on a configuration change? Then the view is recreated but the viewmodel will hold an old reference. You should not hold a reference of your view in the viewmodel. I like to use sealed classes for this.
k
@Ronald van D ViewModel doesn’t hold any reference on view. Basically, VM just send lambda to View and view invokes this lambda on itself.
1
@alex009 I think it’s much easier to make typealias and interface rather than all this classes in example, isn’t it?
a
In sample only interface EventsListener and class EventsDispatcher about this case)
r
@Kirill Prybylsky Ah, misunderstood it. Looks like a fine approach then 🙂.
k
@alex009 ViewModel holds direct reference on the lifecycleOwner, thats ugly.
a
It’s bind like livedata observe, which automatically unsubscribe
k
so dispatcher is like a wrapper of livedata? if so, then ok.
a
Its similar as livedata in automatically unsubscribing, but also guarantee that call will be only once.
k
will take a look, thanks!
m
SingleLiveEvent
is also an option for firing an event once and not hanging on to a reference of it. Only catch is there can be only one Observer