Implementation Ideas
MVVM has many different approaches to its implementation. I will show some of the ways that this pattern can be implemented, but keep in mind that there is no one right approach.
View
The View is pretty straightforward, you're just creating composables to display the information that you need to. In this section I'll just provide some general tips and best practices for creating your View in MVVM:
Always pass the minimum amount of information to your view
This tip helps keep our code debuggable. Let's say we need to navigate from Screen A to Screen B. We have two options. We could pass the entire
navController
down to Screen A, or we could pass a function,navigateToScreenB: () -> Unit
to Screen A. If we pass the entirenavController
, we are also giving Screen A access to many other methods that it could use to influence the screen we are on and our navigation stack. Let's say in the future we have an issue with navigation in our app. If we only passednavigateToScreenB
function to Screen A, then we would instantly have the guarantee that Screen A only navigates to screen B, and we would have to do less debugging on that screen, as opposed to passing the entirenavController
.
Try to minimize business logic in the view
Let's say you're working on Eatery, and you want to determine what the title should show on the home screen. Suppose that if there is more than 1 eatery open, we want to show the text "UAW is not on strike!" is our app title, and if there are no dining halls open, we want to show the text "The strike is still ongoing 😔". It could be tempting to pass the list of Eateries directly to the composable, and have the composable determine which text to show. But it is more appropriate to pass a
screenTitle: String
down to the view. This keeps business logic out of the view and allows you to easily write tests for your ViewModel to determine what your screen displays in what conditions.
ViewModel
I gave an example of a fairly standard ViewModel in my guide on Flows that shows how to incorporate Flows into a ViewModel. Here I'll give an example of another common ViewModel use case: loading an asynchronous resource.
Last updated