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

not fairly How To Deal with ViewModel One-Time Occasions In Jetpack Compose | by Yanneck Reiß | Oct, 2022 will cowl the most recent and most present opinion approaching the world. door slowly correspondingly you comprehend with out issue and accurately. will addition your data cleverly 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 format when deploying Android apps not solely with Jetpack Compose however normally.

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

Within the legacy approach of constructing our person interface with XML layouts, we frequently use the legendary SingleLiveEvent that arose from a Mannequin-View-ViewModel (MVVM) pattern challenge and utilized in many tasks to run such single occasions utilizing LiveData.

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

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

Not solely in that discuss but in addition in one other article on “ViewModel: distinctive occasion anti-patternsIt additionally states that these single occasions must also be represented by that view state.

Additionally, the view mannequin itself shouldn’t be chargeable 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 might be misplaced when utilizing a SharedFlow no replay worth or SingleLiveEvent.

By conserving the occasion within the view state so long as the UI would not inform the view mannequin that the occasion was consumed, we will keep away from that drawback.

Nevertheless, implementing single occasions with this method not solely leads to a variety of normal code, but in addition makes it tough to find out which view state variables needs to be single occasions that have to be consumed or simply easy states. .

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

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

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

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

To get a greater impression, the visualized utility move could be seen within the .gif beneath:

Compose State Occasion Check Software Circulation

The content material composable code for the display screen could be discovered within the code snippet beneath:

As you may 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 through the use of state elevation. The code for the calling composable seems like the next:

We’ll get to dealing with the one-shot occasion state in a second. The principle 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 is able to 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 Evidently that is what Manuel Vivo was speaking about within the article talked about in the beginning.

As defined within the introduction, the anti-pattern is to name your distinctive occasions with out ensuring they’re truly consumed, which may result in surprising habits.

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

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

You possibly can after all merge each into one, however for the sake of readability we’ll depart that out for now.

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

To devour these occasions, we lengthen 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 will implement the prompt approach utilizing the Compose State Occasions library.


To make use of the library, ensure to incorporate the next dependency in your utility 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 crucial 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.

Subsequently, 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 could move a consequence object. In our pattern use case, it’s if the method has completed and we wish to know the timestamp.

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

Through the use of the method 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 useful wrapper known as EventEffect which mechanically 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 perform references the view mannequin perform that may mark the occasion as consumed.

The implementation

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

As a primary step, let’s lengthen the MainViewState which presently solely incorporates 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 an alternative of independently issuing SharedFlow transmits individually, now we use the MainViewState wrapped in it StateFlow not solely to replace the view states, but in addition 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 perform that units our StateEvent capabilities again to consumed price.

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

Now let’s have a look at how we will adapt the anti-pattern model of the MainScreen to devour our StateEvents.

As an alternative of utilizing a LaunchedEffect and acquire 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 could be seen on the physique of the EventEffect You’ll be able to instantly entry the content material of the StateEventContent for additional processing.

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

It’s also possible to try the Gists code snippets in a pattern GitHub repository:

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

We’ve mentioned the anti-patterns introduced to implement single occasions after which check out the Compose State Eventy library which gives a useful answer to implement the prompt approach by dealing with these occasions by way of the view mannequin’s view state object.

After studying this text the query might come up. “Why not use the standard approach 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 in addition makes it clear instantly in our respective ViewState which occasions needs to be consumed by the UI layer and which ought to solely be rendered. One might argue that this needs to be left fully to the view layer, however follow has proven that view state information courses can develop quickly and thus grow to be unwieldy with regards to remembering which occasions they’re meant to be one. non permanent occasions and that solely fake to characterize the state.

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

I hope you had some conclusions, clap your fingers if you happen to preferred my article, make certain to join e mail notifications. and observe for extra!

I want the article roughly How To Deal with ViewModel One-Time Occasions In Jetpack Compose | by Yanneck Reiß | Oct, 2022 provides notion to you and is beneficial for surcharge to your data

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