VolodymyrH
VolodymyrH

Reputation: 2019

How to properly deliver events from the ViewModel?

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

Answers (1)

Jeel Vankhede
Jeel Vankhede

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 :

  • Let's say your ViewModel has a asynchronous method that you want to deliver result on UI.
  • Take a interface object of your result type that provides interaction between your ViewModel & Activity/Fragment, on your async method from ViewModel pass your LifeCycleOwner object and interface object as method parameter.
  • Now check in your method about your lifecycle events of your LifecycleOwner (i.e. activity or fragment instance here) and provide callback by interface on your UI.
  • So, now you can mark your result as null once delivered to UI.

It's bit of setup, but will work when you want solution without LiveData.

Upvotes: 1

Related Questions