Augusto Carmo
Augusto Carmo

Reputation: 4964

Best way to communicate click events between fragments (using ViewModel)

I was wondering about what is the best way to tell different observers (fragments) that a click event happened, using ViewModel.

I found this article on the web that shows a way, but it is not useful if more than one observer is interested on the click event (because as long as the first observer gets the value, it'll return null for the next observer).

Upvotes: 0

Views: 306

Answers (1)

tyczj
tyczj

Reputation: 73753

If you are ok with using experimental kotlin features I would suggest SharedFlow

you can expose an instance from your view model (assuming its the same view model instance in each fragment) and they can all observe it.

SharedFlow can be configured so that it only emits when new values are sent or it can give you the current value when you subscribe unlike LiveData which always gives you the latest value which you might not be interested in

Upvotes: 1

Related Questions