How To Deal with ViewModel One-Time Occasions In Jetpack Compose | by Yanneck Reiß | Oct, 2022 | Area Tech

kind of How To Deal with ViewModel One-Time Occasions In Jetpack Compose | by Yanneck Reiß | Oct, 2022 will cowl the newest and most present steerage simply concerning the world. door slowly in consequence you perceive nicely and accurately. will progress your information proficiently and reliably

A few new technique to implement single occasions in Jetpack Compose utilizing the Compose state occasion library

sureDealing with states and occasions is simply as important as creating the precise structure when deploying Android apps not solely with Jetpack Compose however on the whole.

In most functions, one will come to some extent the place we have to implement one time both “distinctive” occasions. These occasions are actions that the consumer interface ought to execute solely as soon as. An instance of such an occasion is the response to a profitable API name which might be visualized by presenting a Snackbar for example.

Within the legacy manner of constructing our consumer interface with XML layouts, we regularly use the legendary SingleLiveEvent that arose from a Mannequin-View-ViewModel (MVVM) pattern mission and utilized in many initiatives to run such single occasions utilizing LiveData.

With the rise of Kotlin’s scorching stream courses, SharedFlow it was typically launched as a substitute for the SingleLiveEvent.

Nonetheless, with Jetpack Compose’s declarative UI strategy, issues modified. For instance, as Manuel Vivo suggests in his speak at Droidcon Berlin 2022 on “Implementing Fashionable Android Structure”it is a good suggestion to carry the UI state inside an information class contained in the view mannequin, which is then introduced to the UI layer.

Not solely in that speak but additionally in one other article on “ViewModel: distinctive occasion anti-patternsIt additionally states that these single occasions also needs to be represented by means of that view state.

Additionally, the view mannequin itself shouldn’t be accountable for figuring out whether or not the occasion has been dealt with. If such a single occasion is known as and the UI is idle, the occasion could possibly be misplaced when utilizing a SharedFlow no replay worth or SingleLiveEvent.

By conserving the occasion within the view state so long as the UI does not inform the view mannequin that the occasion was consumed, we are able to keep away from that downside.

Nonetheless, implementing single occasions with this strategy not solely leads to lots of customary code, but additionally makes it tough to find out which view state variables must be single occasions that should be consumed or simply easy states. .

A brand new strategy to ease this course of and make our view states a lot simpler to take care of is the Compose state occasions library of my colleague Leonard Palm.

On this article, we are going to see a sensible instance. We are going to see how we are able to use this library to implement our distinctive occasions in a manner that’s geared in direction of the cussed structure pointers proposed by the now on android gear.

Let’s discuss a fast instance. We now have a easy consumer interface with two buttons. Every of them triggers a dummy course of in our view mannequin, which finally triggers a single occasion that means the method has completed.

The occasion is then displayed as Snackbar by the consumer interface layer.

To get a greater impression, the visualized software stream might be seen within the .gif under:

Compose State Occasion Check Utility Circulate

The content material composable code for the display screen might be discovered within the code snippet under:

As you possibly can see, it is only a nested Column design containing a TopAppBartwo buttons and one CircularProgressIndicator displayed dynamically when the add course of is operating.

we name this MainContent composable by utilizing state elevation. The code for the calling composable seems to be like the next:

We’ll get to dealing with the one-shot occasion state in a second. The primary takeaway from this code snippet is the gathering of the MainViewState held by him MainViewModel.

Along with point out is that we wrap the MainContent in a Scaffold to enter a SnackbarHost which can then be used to invoke the Snackbar at every of the distinctive occasions.

Earlier than reaching the Compose state occasions technique to implement one-time occasions, let’s check out what the anti-pattern Plainly that is what Manuel Vivo was speaking about within the article talked about firstly.

As defined within the introduction, the anti-pattern is to name your distinctive occasions with out ensuring they’re really consumed, which might result in sudden conduct.

To indicate this, let’s check out an implementation for our display screen with that anti-pattern:

As you possibly can see, to name occasions in a single go we make use of SharedFlow. We now have two separate streams. One for the completed course of with out and one for the case with a time stamp.

You possibly can in fact merge each into one, however for the sake of readability we’ll go away that out for now.

the startProcess(..) The operate is known as from every of our button callbacks with the respective enter parameter to ship a timestamp on completion or failure.

To eat these occasions, we prolong the one proven above MainScreen composable with a brand new LaunchedEffect which then again collects our two SharedFlow streams in a repeatOnLifecycle(..) Physique.

the respective Snackbar is then proven calling SnackbarHostState which acts as enter for the beforehand proven Scaffold that wraps the MainContent.

Now that we have seen the antipattern, let’s check out how we are able to implement the advised manner utilizing the Compose State Occasions library.


To make use of the library, ensure that to incorporate the next dependency in your software stage construct.gradle proceedings. On the time of writing the library, the model is in 1.1.0:

Compose state occasions

The aim of the library is important to ease the method of transferring these one-time occasions away from their very own streams into the view state of their respective streams. ViewModel class.

Due to this fact, the library introduces two new courses.

  • StateEvent: Can be utilized for easy one-time occasion state representations, in our pattern use case if the method has completed with no additional state implications.
  • StateEventWithContent<T>: Can be utilized for one-time occasion state representations the place you have to cross a outcome object. In our pattern use case, it’s if the method has completed and we need to know the timestamp.

Every of the courses might be within the consumed both triggered situation.

Through the use of the strategy of constructing single occasions into your view state object, you all the time have the case of the state illustration and inform the view mannequin that it was consumed.

As a result of in Jetpack Compose you’ll deal with this case with the LaunchedEffectthe library is available in a helpful wrapper referred to as EventEffect which robotically handles this course of.

It solely requires the next two enter parameters:

  • occasion: The StateEvent both StateEventWithContent reference of their respective view state.
  • onConsumed: The operate references the view mannequin operate that may mark the occasion as consumed.

The implementation

Now that you already know the fundamentals of the library, let’s check out how we are able to migrate the antipattern instance to make use of the Compose State Occasions library.

As a primary step, let’s prolong the MainViewState which at present solely comprises the load state with the Compose State Occasions objects for our two distinctive occasions.

Now that we replace the MainViewStatewe’re going to migrate the ViewModel class accordingly:

As a substitute of independently issuing SharedFlow transmits individually, now we use the MainViewState wrapped in it StateFlow not solely to replace the view states, but additionally to name our distinctive occasions.

To set them to the “invoked” state, we set the StateEvent objects to the triggered situation.

We additionally launched a brand new operate that units our StateEvent features again to consumed price.

In an actual world instance, you’ll need to use two particular person features to set this consumption state.

Now let’s examine how we are able to adapt the anti-pattern model of the MainScreen to eat our StateEvents.

As a substitute of utilizing a LaunchedEffect and gather from particular person SharedFlow flows, we now introduce the beforehand mentioned EventEffect which comes with the Compose State Occasions library.

First EventEffect the overload takes the untimestamped model of the one occasion and the timestamped second as content material. As might be seen on the physique of the EventEffect You possibly can instantly entry the content material of the StateEventContent for additional processing.

On this case, we embody it within the Snackbar message.

You may also take a look at the Gists code snippets in a pattern GitHub repository:

On this article, we have now collected the opinionated Android structure from the Now in Android group. Specifically, we check out the advised cause for implementing single occasions when utilizing Jetpack Compose as your UI system.

We now have mentioned the anti-patterns introduced to implement single occasions after which check out the Compose State Eventy library which offers a helpful answer to implement the advised manner by dealing with these occasions through the view mannequin’s view state object.

After studying this text the query might come up. “Why not use the traditional manner with out utilizing the Compose State Occasions library?”.

Utilizing the Compose State Occasions library not solely makes it simple to course of single occasions, but additionally makes it clear instantly in our respective ViewState which occasions must be consumed by the UI layer and which ought to solely be rendered. One may argue that this must be left fully to the view layer, however apply has proven that view state information courses can develop quickly and thus turn out to be unwieldy on the subject of remembering which occasions they’re meant to be one. momentary occasions and that solely faux to characterize the state.

In conclusion, I can solely encourage you to strive the library for your self.

I hope you had some conclusions, clap your palms should you favored my article, be certain to join electronic mail notifications. and comply with for extra!

I want the article about How To Deal with ViewModel One-Time Occasions In Jetpack Compose | by Yanneck Reiß | Oct, 2022 provides keenness to you and is helpful for including collectively to your information

How To Handle ViewModel One-Time Events In Jetpack Compose | by Yanneck Reiß | Oct, 2022