ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Traditional MVVM with Jetpack Compose and StateFlow

Anastasia Finogenova
ProAndroidDev
Published in
5 min readJan 23, 2022

With the introduction of Jetpack Compose some developers may assume that using it requires a different architectural approach to how you build Android app. People start mentioning the mysterious UDF 🕵️‍♀️. My goal today is to show how you can adapt the base principals of MVVM we have used for years but with the Compose UI.

Disclaimer: MVVM is UDF or at least it should be implemented that way 😉.

Let’s refresh what we know about MVVM and establish some theory here.

For the recap purposes and to make sure we are on the same page of what MVVM is (based on my experience that is something we need to clarify before entering a conversation 😅 ), here is a quick diagram I put together that also reflects how my mini app works.

As you can see, there is no revelations here. Just old good base stuff you may already have seen several times when speaking about MVVM and representing it.

We have the Model layer containing the data source which is accessed through a repository. There is the ViewModel containing State and all the logic acting as a mediator between the datasource and View. The main difference is in the View layer where our Jetpack Compose code will reside.

Just a note on MVVM in general — when using this pattern no matter with Compose or not you need to make sure that you have a uni-directional data flow (yes! UDF). That basically means that View doesn’t push or change State in ViewModel. ViewModel will provide State in response of Events coming from View (for example, clicks or user input).

For more info on my recommended MVVM approach check my other article.

For the StateFlow part — we need a way to observe State and notify our View of changes. There is multiple ways to do it and there is definitively an evolution of widely used libraries and API. From the recent ones we can consider LiveData but the thing is Compose was designed in Kotlin for Kotlin…

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (4)

Write a response