In the Android/Kotlin world, there are 2 ways to provide the state from the ViewModel layer to the View layer: single state and multiple states. Which one is better? Let’s do some overview of the pros and cons of both methods.

High-level thoughts

Single state is nice at first glance. A single data class contains all fields, ensuring a consistent state. However, it requires additional effort under the hood: if there are several data sources for the state, then you need a synchronized section to update the state. Otherwise, you may end up with some concurrency-related issues. Also, this way may cause excessive updates or equality checks in the View layer, especially if we are talking about Jetpack Compose.

On the other hand, multiple states provide a more verbose external contract for ViewModel but there is no need for additional synchronization, each data field is independent by default, and Jetpack Compose can read state exactly where it’s needed.

The case

Let’s do a comparison on a small screen with 3 variables:

  • Title
  • Text from a text field
  • Loading state

When the screen opens, 2 data sources are loaded: title and text. During loading, the loading state must be true. Additionally, the text can be changed based on user input.

Code comparison

💡 Note: I’ll try to keep this as simple as possible. For this reason I won’t use redux-like methods. There are also other simplifications, such as no error handling. Please let me know in the comments if you think anything could be improved in this comparison.

💡 Note: I’ll skip the View layer to keep this article short.

One thing that will be constant for both cases is repository. With some simplifications, it will be like this:

class SomeRepository {

suspend fun getTitle(): String {
delay(500)
return "Some Title"
}

suspend fun getSavedFieldText(): String {
delay(1000)
return "Saved Field Text"
}
}

It’s just a stub that emulates some data loading. Now let’s move to the interesting part.

Source link