ViewModel occasions are actions originated from the ViewModel that the UI ought to carry out. For instance, displaying an informative message to the person, or navigating to a distinct display when the appliance state modifications.
Our steering on ViewModel occasions is opinionated in two alternative ways:
At any time when a one-off occasion originates within the ViewModel, the ViewModel ought to deal with that occasion instantly inflicting a state replace. The ViewModel ought to solely expose utility state. Exposing occasions that haven’t been decreased to state from a ViewModel means the ViewModel isn’t the supply of reality for the state derived from these occasions; Unidirectional Information Circulation (UDF) describes some great benefits of sending occasions solely to shoppers that outlive their producers.
State needs to be uncovered utilizing an observable knowledge holder sort.
In your app, you is perhaps exposing ViewModel occasions to the UI utilizing Kotlin Channels or different reactive streams similar to SharedFlow, or possibly it is a sample you’ve seen in different tasks. When the producer (the ViewModel) outlives the patron (UI—Compose or Views), which might be the case with ViewModel occasions, these APIs don’t assure the supply and processing of these occasions. This may end up in bugs and future issues for the developer, and it’s additionally an unacceptable person expertise for many apps.
It is best to deal with ViewModel occasions instantly, inflicting a UI state replace. Attempting to show occasions as an object utilizing different reactive options similar to Channel or SharedFlow doesn’t assure the supply and processing of the occasions.
Right here’s an instance of the implementation of a ViewModel in an app’s typical funds circulate. Within the following code snippets, the MakePaymentViewModel instantly tells the UI to navigate to the cost end result display when the results of the cost request comes again. We’ll use this instance to discover why dealing with one-off ViewModel occasions like this brings issues and better engineering prices.