Let’s change how we build things!

What if we can change this situation, giving the ViewModel , or way better — the ViewState — the power to build the UI, and letting the View only render it? That’s possible thanks to Jetpack Compose.

HURRAY!

So, what do we need to change?

The MVIViewState class will be a little bit different:

This class is pretty verbose, and there’s a reason for it: ViewState should represent the View , so it should know how to render it, right?

By adding a

function to the ViewState we force every subclass to define it, that means that every child-class will know how to “render” its state. In this way, inside the ViewState class, we build our View accordingly to the ViewState . This will allow us to have a leaner View (Activity or Fragment).

So, what about the ViewModel class or the Activity/Fragment ? Well, the ViewModel basically remains the same:

Okok, and the View ?

HERE it is! Isn’t it beautiful?

I personally love how the view just became really lean and basically doesn’t do anything. I̶t̶ ̶o̶b̶s̶e̶r̶v̶e̶s̶ ̶t̶h̶e̶ ̶L̶i̶v̶e̶D̶a̶t̶a̶ ̶a̶n̶d̶ ̶t̶h̶a̶t̶’̶s̶ ̶i̶t̶.̶ ̶T̶h̶r̶o̶u̶g̶h̶ ̶t̶h̶e̶ ̶s̶e̶t̶C̶o̶n̶t̶e̶n̶t̶ ̶{̶}̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶f̶r̶o̶m̶ ̶t̶h̶e̶ ̶J̶e̶t̶p̶a̶c̶k̶C̶o̶m̶p̶o̶s̶e̶ ̶l̶i̶b̶r̶a̶r̶y̶,̶ ̶w̶e̶’̶r̶e̶ ̶n̶o̶w̶ ̶a̶b̶l̶e̶ ̶t̶o̶ ̶d̶o̶ ̶t̶h̶i̶s̶ ̶m̶a̶g̶i̶c̶ ̶t̶r̶i̶c̶k̶!̶

EDIT: thanks to Leland Richardson and his suggestions the View is now even better.