Reputation: 2019
I need some way to deliver events that should be done only once from the ViewModel. Currently, I'm using LiveData for this. Use case:
I'm building some intent and then I should deliver it to fragment. The problem is obvious, after rotate, I get old data and startAtivity runs once again. I don't want to use some hacks with checks, etc. I'm sure there's should be the correct way to do such things. The only way I've found is here: link - SingleLiveEvent.
So, is it a correct way to do such things? What is the correct way to deliver UI dependent events from the ViewModel?
Upvotes: 1
Views: 85
Reputation: 12138
Is it a correct way to do such things?
Answer to this question is yes, if that does the job without leaking any objects at all than you've probably found right solution !.
What is the correct way to deliver UI dependent events from the ViewModel?
Above solution you've found out is okay in your use-case, but if you're finding a solution that don't involve LiveData
at all than i might be able to point it to one direction. Check out a solution below :
ViewModel
has a asynchronous method that you want to deliver result on UI.ViewModel
& Activity/Fragment
, on your async method from ViewModel
pass your LifeCycleOwner object
and interface object
as method parameter.LifecycleOwner
(i.e. activity or fragment instance here) and provide callback by interface on your UI.It's bit of setup, but will work when you want solution without LiveData
.
Upvotes: 1