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

Kirill Prybylsky

02/13/2020, 9:17 AM
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

alex009

02/13/2020, 11:42 AM
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

Ronald van D

02/13/2020, 1:14 PM
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

Kirill Prybylsky

02/13/2020, 1:17 PM
@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

alex009

02/13/2020, 1:27 PM
In sample only interface EventsListener and class EventsDispatcher about this case)
r

Ronald van D

02/13/2020, 1:28 PM
@Kirill Prybylsky Ah, misunderstood it. Looks like a fine approach then 🙂.
k

Kirill Prybylsky

02/13/2020, 1:31 PM
@alex009 ViewModel holds direct reference on the lifecycleOwner, thats ugly.
a

alex009

02/13/2020, 1:34 PM
It’s bind like livedata observe, which automatically unsubscribe
k

Kirill Prybylsky

02/13/2020, 1:35 PM
so dispatcher is like a wrapper of livedata? if so, then ok.
a

alex009

02/13/2020, 1:37 PM
Its similar as livedata in automatically unsubscribing, but also guarantee that call will be only once.
k

Kirill Prybylsky

02/13/2020, 1:37 PM
will take a look, thanks!
m

mng

02/13/2020, 5:43 PM
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
6 Views