Blog Infos
Author
Published
Topics
Published

Photo by Glenn Carstens-Peters on Unsplash

 

An important aspect of creating a delightful user experience is handling actions from users and presenting the ‘right state’ based on the action.

In days gone by, working with older view systems, we had a fairly common accepted way to expose live data or state from the view model, observe it in activities or fragments and act on it to render a new UI state or some side effects.

In Compose world, we initially started off passing view models to screens and progressed to passing lambdas for user actions

It’s common to use lambdas to represent each action that a user performs on a screen. For instance, consider the following example.

MyModelScreen(
          items = item.data,
          onSave = viewModel::addMyModel,
          modifier = modifier
      )

Here we pass, onSave = viewModel::addMyModel which works flawlessly.

As the adoption of jetpack compose and declarative UIs increase, we commonly observe state hoisting and lambda functions scattered around.

As code grows, it becomes increasingly complex and messy. If we take a look at a more complex screen (for example in my case):

I was working on a checkout screen, that involves multiple actions including delivery date selection, order note input, item management & actions like adding, updating, or deleting items, as well as the ability to cancel or place an order, we would have to pass an extensive number of lambda functions. In my case, it would amount to at least 20 different lambda functions.

Let’s imagine we had to add more actions on this screen. The code might look something like this, which is perfectly functional and runs smoothly.

MyModelScreen(
            items = item.data,
            onSave = viewModel::onSaveClicked,
            onAdd = viewModel::onAddClicked,
            onUpdate = viewModel::onTextUpdate,
            onDelete = viewModel::onDeleteClicked,
            onList = viewModel::onListClicked,
            modifier = modifier
        )

This would only grow as we keep on adding new functionalities.

Separating state and events with a clear understanding can improve code readability, maintainability, and testability.

Exploring the Benefits of the Command Pattern to Streamline Complex Screens

This led me to consider utilising the principles of the Command Pattern to address this issue. According to its definition, this pattern involves encapsulating a request as an object, allowing for greater flexibility in terms of parameterising clients with various requests, organising requests in queues or logs, and providing support for undoing operations.

Basic terminology before we move ahead:

Receiver: The object that receives and executes the command (ViewModel in our case).

Invoker: The object that sends the command to the receiver. (Buttons etc.)

Command Object: The command Itself, that implements the execute method (see below eg.AddCommand), has all necessary info. to get the action done

Client: The application or component that is aware of the Receiver, Invoker etc (Roughly matches our activity).

Step 1: Set up Command Receiver and Commands like given below

The Command pattern encapsulates a request in an object, which enables us to store & pass the command to a method, and return the command like any other object.

We start off by defining a command receiver that acts as a contract for all actions available to the user for the given screen.

Then we move to Command itself that has one method executes, all the actions on this screen implement this method.

Write a Command Receiver and implementation for all commands (actions) that are allowed for users on the given screen.

interface CommandReceiver {
fun onAddClicked()
fun onTextUpdate(newText: String)
fun onDeleteClicked()
fun onListClicked()
fun onSaveClicked(text: String)
fun processCommand(command: Command) {
command.execute(this)
}
}
interface Command {
fun execute(receiver: CommandReceiver)
}
class AddCommand : Command {
override fun execute(receiver: CommandReceiver) {
receiver.onAddClicked()
}
}
class TextUpdateCommand(private val newText: String) : Command {
override fun execute(receiver: CommandReceiver) {
receiver.onTextUpdate(newText)
}
}
class DeleteProductCommand : Command {
override fun execute(receiver: CommandReceiver) {
receiver.onDeleteClicked()
}
}
class ListCommand() : Command {
override fun execute(receiver: CommandReceiver) {
receiver.onListClicked()
}
}
class SaveCommand(private val text: String) : Command {
override fun execute(receiver: CommandReceiver) {
receiver.onSaveClicked(text)
}
}

Step 2: Update ViewModel execute commands

Since ViewModel implements the contract CommandReceiver it also implements actions for all commands.

class MyModelViewModel @Inject constructor(
private val myModelRepository: MyModelRepository
) : ViewModel(), CommandReceiver {
override fun onAddClicked() {
viewModelScope.launch {
Log.v(TAG, "add command")
}
}
override fun onTextUpdate(newText: String) {
viewModelScope.launch {
Log.v(TAG, "edit command")
}
}
override fun onDeleteClicked() {
viewModelScope.launch {
Log.v(TAG, "delete command")
}
}
override fun onListClicked() {
viewModelScope.launch {
Log.v(TAG, "list command")
}
}
override fun onSaveClicked(text: String) {
viewModelScope.launch {
myModelRepository.add(text)
}
}
companion object {
const val TAG = "MyTag"
}
}

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

Step 3: Remove all lambdas for actions and pass command processor.

//Before
MyModelScreen(
            items = items.data,
            onSave = viewModel::onSaveClicked,
            onAdd = viewModel::onAddClicked,
            onUpdate = viewModel::onTextUpdate,
            onDelete = viewModel::onDeleteClicked,
            onList = viewModel::onListClicked,
            modifier = modifier
        )
//After
MyModelCommandScreen(
    items = items.data,
    modifier = modifier,
    commandProcessor = viewModel::processCommand
)

Step 4: Commands from Screen to ViewModel (command pattern in action!).

We now pass commands as objects to the command receiver that executes

Icon(
modifier = Modifier.clickable { commandProcessor(AddCommand()) },
imageVector = Icons.Filled.Add,
contentDescription = "add"
)
Icon(
modifier = Modifier.clickable { commandProcessor(TextUpdateCommand(nameMyModel)) },
imageVector = Icons.Filled.Edit,
contentDescription = "edit"
)
Icon(
modifier = Modifier.clickable { commandProcessor(DeleteProductCommand()) },
imageVector = Icons.Filled.Delete,
contentDescription = "delete"
)
Icon(
modifier = Modifier.clickable { commandProcessor(ListCommand()) },
imageVector = Icons.Filled.List,
contentDescription = "list"
)
}
view raw Screen.kt hosted with ❤ by GitHub

While it may seem tempting to use this in all components, it is recommended to use it only for screen-level composables (which are close to the root)

For component level design, this approach may adversely affect re-usability, and we would prefer components not to directly manipulate screen state.

Here is the link to the GitHub repository where you can see it in action.

Special thanks to Merab Tato Kutalia & Himanshu Singh for helping me write this 🙌

Thank you for reading!

This article was previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu