Two screens need the same warning. Where should the state live?
Imagine an Android app with two screens: an order history screen and an account screen. Both need to warn the user when an earlier order needs attention. From either screen, the user can open a dialog, dismiss it or start a recovery action. The first version might put the logic in the order history ViewModel. Then the account screen needs it too. Sharing the recovery use case helps. Both…
In an Android app with two screens, both an order history screen and an account screen, it's necessary to warn users when an earlier order needs attention. One screen might handle this warning logic in its ViewModel, but when the other screen also requires the same functionality, sharing the warning use case helps streamline the code. However, extracting this behavior into a small presentation component presents its own challenges.
The component could manage the state needed to show the warning and handle user actions such as dismissing or recovering. But deciding when to show the warning, hold the dialog state, and process user actions remains a duplicate task between the ViewModels. One option is to create an interface that defines the warning state and provides functions to check, dismiss, and recover. Each ViewModel then uses this interface to handle the warning behavior.
Another option is to separate the decision of dismissing the warning from the underlying order status. Dismissing a warning shouldn't automatically mark the order as recovered, as this changes the app's knowledge about the order. Similarly, recovery actions may need to be handled carefully to ensure they only occur once.
The UI component could be added to the screen's state flow, allowing it to be observed alongside other screen state. This approach keeps the warning behavior separate but still allows the UI to manage it effectively. Alternatively, sharing a ViewModel at a higher level of navigation could make sense if the warning belongs to that shared flow.
Before deciding on a pattern, it's essential to consider various scenarios, such as dismissing the warning on one screen and opening the other, starting recovery and leaving the screen, triggering recovery multiple times, or reopening the app while the order still needs attention. These cases help distinguish which state belongs to the screen and which should be shared. Ultimately, the decision should be based on whether the warning behavior makes the screens and their tests easier to understand.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.