roughly Easy methods to deal with single ViewModel occasions in Jetpack Compose | by Yanneck Reiss | October 2022
will cowl the newest and most present data happening for the world. gate slowly in view of that you just perceive with out problem and accurately. will deposit your information dexterously 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 usually.
In most purposes, one will come to a degree 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 may be visualized by presenting a Snackbar
for example.
Within the legacy method of constructing our person interface with XML layouts, we regularly use the legendary SingleLiveEvent
that arose from a Mannequin-View-ViewModel (MVVM) pattern venture and utilized in many tasks to run such single occasions utilizing LiveData
.
With the rise of Kotlin’s sizzling stream lessons, SharedFlow
it was usually launched as a substitute 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 Trendy Android Structure”it is a good suggestion to carry the UI state inside an information class contained in the view mannequin, which is then offered 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 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 might be misplaced when utilizing a SharedFlow
no replay worth or SingleLiveEvent
.
By holding 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.
Nevertheless, implementing single occasions with this method not solely leads to loads of normal code, but in addition makes it troublesome to find out which view state variables ought to be single occasions that must 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 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 method that’s geared in 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 software movement may be seen within the .gif beneath:
The content material composable code for the display screen may be discovered within the code snippet beneath:
As you possibly can see, it is only a nested Column
design containing a TopAppBar
two 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 appears to be like 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 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 at first.
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 surprising conduct.
To point out 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’ve two separate streams. One for the completed course of with out and one for the case with a time stamp.
You may in fact 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 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 urged method utilizing the Compose State Occasions library.
Setting
To make use of the library, make certain to incorporate the next dependency in your software degree 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 shifting 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 lessons.
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 should move a end result object. In our pattern use case, it’s if the method has completed and we need to know the timestamp.
Every of the lessons may 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 LaunchedEffect
the library is available in a useful wrapper known as EventEffect
which routinely handles this course of.
It solely requires the next two enter parameters:
occasion
: TheStateEvent
bothStateEventWithContent
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 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 incorporates the load state with the Compose State Occasions objects for our two distinctive occasions.
Now that we replace the MainViewState
we’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 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
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 devour our StateEvents
.
As a substitute 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 only occasion and the timestamped second as content material. As may be seen on the physique of the EventEffect
You may instantly entry the content material of the StateEventContent
for additional processing.
On this case, we embody it within the Snackbar
message.
You can too take a look at the Gists code snippets in a pattern GitHub repository:
On this article, we’ve got collected the opinionated Android structure from the Now in Android group. Particularly, we check out the urged purpose for implementing single occasions when utilizing Jetpack Compose as your UI system.
We’ve mentioned the anti-patterns offered to implement single occasions after which check out the Compose State Eventy library which offers a useful resolution to implement the urged method 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 method 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 ought to be consumed by the UI layer and which ought to solely be rendered. One may argue that this ought to be left completely to the view layer, however observe has proven that view state knowledge lessons can develop quickly and thus turn out to be unwieldy in relation to 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 fingers if you happen to favored my article, be certain to enroll in e mail notifications. and observe for extra!
I hope the article roughly Easy methods to deal with single ViewModel occasions in Jetpack Compose | by Yanneck Reiss | October 2022
provides acuteness to you and is helpful for including as much as your information
How to handle single ViewModel events in Jetpack Compose | by Yanneck Reiss | October 2022