I’m experimenting with sharing features across dif...
# android
j
I’m experimenting with sharing features across different view models without using abstract classes. I came up with a pattern leveraging interface delegation, I think I like it but I need an external opinion. A concrete example: The app I work on let users pay for public transport tickets, 2 screens need to check sale statuses to warn the users if something went wrong with a previous payment. The idea is that when a user navigate to a screen, its view model make a check on the sale database, check if there are any “corrupted” sales and let the UI show a dialog with a warning message. To share that ability I created an interface with a default implementation that any ViewModel can use:
Copy code
interface CorruptedSaleChecker {
    val corruptedSalesInfo: State<UserInfo.CorruptedSales?>
    suspend fun promptIfCorruptedSales()
    suspend fun resolveCorruptedSales()
    fun dismissCorruptedSales()
}

class DefaultCorruptedSaleChecker() { ... }

class SaleHistoryViewModel(
    ...,
    corruptedSaleChecker: CorruptedSaleChecker,
) : ViewModel(),
    ... // other shared capabilities, not tied to ViewModel from android
    CorruptedSaleChecker by corruptedSaleChecker {
    ...
}
This way I can share the logic to show and hide dialog + the “action” (
resolveCorruptedSales
in this case) so a user can trigger it through a button later on if they don’t want to do whatever the dialog is recommending when navigating to the screen. I did think of having a composable with a dedicated view model that would own all the logic to check statuses and ui logic for the dialog, but I would miss the ability of triggering the action from outside the dialog. What do you all think of that? Have you solved something similar in another way?
One thing I’m not really happy with is exposing a
State
object from the interface. My view models have a centralized
StateFlow<ScreenState>
property that let the UI observe a single source of state, but now I have two or more if more capabilities are shared.
r
hi Jean, I feel like that’s a bit of re-inventing the wheel and it could apply just some existing patterns. If you look at all the “clean-code” and “architecture” documentations it usually shows cake-layers (or a circle) that I’ll sum up here:
Copy code
User Interface
-------------
View Model
-------------
Use Cases
-------------
Repositories
-------------
Services


(reminder I'm not advocating to anyone to implement all this on their app, those are established tools and patterns and it's up to us to apply accordingly when needed)
So there’s two patterns there between ViewModel and Service that could be applied to your case. There’s
CheckCorruptSalesUseCase
or a
SalesRepository
that can implement the business logic. Then the ViewModel just receive an instance of this UseCase/Repo via the dependency injection. Given you got 4 functions together, maybe a repository is the winner here to group together them. /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ Your other question is about the
ScreenState
. And I would definitely favour a single State coming from the ViewModel. What I’ve done in the past is to add the re-usable state inside the screen state. For example:
Copy code
data class MyScreenState (
   val id: String,
   val a: Something,
   val b: OtherSomething,
   val corruptedSales: UserInfo.CorruptedSales?
)
this can be trivially combined using
combine(Flow<T>, Flow<R>): Flow<O>
. And similar pattern to add it to user interaction/events:
Copy code
enum class CorruptedSalesEvents {
  Prompt, Resolve, Dismiss
}
// and then in the ViewModel
sealed class ScreenUiEvents {
  data object OnCtaTap: ScreenUiEvents()
  data class OnCorruptedSales(val event: CorruptedSalesEvents): ScreenUiEvents()
}
this makes it easy to build your re-usable composable based only on
UserInfo.CorruptedSales?
and
CorruptedSalesEvents
but the API between any ViewModel and any Screen in the whole project is always consistent containing 1 ScreenState and 1 ScreenEvents. Does that make sense? I hope it helps.
j
Hi! I do use both usecases and repositories, and
CorruptedSaleChecker
build on top of it. The implementation of
suspend fun resolveCorruptedSales()
from the interface is the use case. I did have the use case as a dependency in each view model and they all had a state with
val corruptedSales: UserInfo.CorruptedSales?
like you described. It works fine but I felt like it was “a lot” of duplicated code to add the feature where it’s needed.
r
I’m not sure I follow exactly what’s currently in your current code, but it seems like if those 4 functions are coming from and implemented in the Repository, I don’t see that much code duplication to
combine<>
the data into 1 stream, and whenever the user send events to the ViewModel, it simply
viewModelScope.launch { repo.resolveCorruptSales() }
Also important to just repeat the warning:
Copy code
I'm not advocating to anyone to implement all this on their app, those are established tools and patterns and it's up to us to apply accordingly when needed
Are you saying that you made a repository, and then use cases and then to the ViewModel? Cause that I agree it’s a funny overkill.
just to be more clear with an example, here’s what I would be suggesting:
Copy code
class MyViewModel(
  private val salesRepo: CorruptedSaleChecker
): ViewModel() {

  private val viewModelData = MutableStateFlow<Something>
  val state: StateFlow<ScreenState> = combine(viewModelData, salesRepo.corruptedSalesInfo) { state, sales ->
  ScreenState(state.foo, state.bar, sales)
}

fun onUiEvent(event: UiEvent) = when(event) {
  is PromptCorruptedSales -> viewModelScope.launch { salesRepo.promptIfCorruptedSales() }
}
  is ... other events

}
it’s just the ViewModel delegating the sales checking to something else.
j
We structured our code a bit differently: • Repositories for us are not aggregate of functionalities. We call repositories classes aggregating access to data. Like
SaleRepository
abstracting all the calls to our Room database. •
ResolveCorruptedSales
is our usecase, a pure domain logic function indenpendent of Room (through
SaleRepository
and from Android). • Then our view model has a dependency on
ResolveCorruptedSales
The duplication I talked about is that we need the same code combining whatever comes from the usecase in the screen state, and the
onUiEvent
. We have
UiEvent
equivalent types but we limit them to each screen, so it means the same events in each screens too. What I tried with the interface delegation was to group the usecase dependency, event handling and state handling in one “capability class” that each view model can use. It’s really just an experimentation, I could keep the code we have that is very similar to what you say.
r
I understand what you mean. To be fair the example I wrote is not exactly the way I work, I have my own oddities that is for a totally different discussion, so it was just an example.. And regarding the combine/event duplication on the ViewModel maybe depends a lot on how it’s structured. I did similar on the past exactly like:
Copy code
// reusable component
// state
data class ReusableState(....)
// event
enum class ReusableEvent { ... } // or maybe it is a sealed class
// handling:
val state: StateFlow<ReusableState>
fun onReusableEvent(event: ReusableEvent) { ...
then on the ViewModel:
Copy code
data class ScreenState(
  val reusableState: ReusableState,
... other
)
sealed class ScreenEvent {
  data class OnReusableEvent(val event: ReusableEvent): ScreenEvent
}
this leads IMHO the ViewModel code duplication to be a matter of 4 lines of code. The combine as example on my previous message, and the event like:
Copy code
when(screenEvent) {
  is OnReusableEvent -> reusable.onReusableEvent(screenEvent.event)
}
So the ViewModel just encapsulates the models from the different layer and then delegates its actions to it. But yes, I agree there’s a little repetition that I worked around by structuring the ViewModel and the other layer in manner to minimize it.
( but on the other hand, I get you, it’s fun to do those R&D and see what else it’s possible, maybe you’re onto something cool )
c
I've used the delegation pattern you've described in a few projects to create a sort of "plug and play" set of reusable presentation features. I've found it works well. This is different from use cases for sharing business logic; but rather I found it useful for exposing reusable presentation/state of UI components. I'd recommend watching -

https://youtu.be/18D8mCfzWRA?is=Z-tvNaUgKE8hzTpN▾

It gives a deeper dive into similar patterns and it was inspiration for me when exploring this sort of pattern
s
Hi. I’d be curious about how you scope the
CorruptedSaleChecker
instance across the two ViewModels. If they share an instance, should dismissing the warning on one screen also dismiss it on the other? If each has its own instance, what should happen if both try to resolve the same sale? It might be useful to test those two cases explicitly. I haven’t tried this with your implementation, but it seems like a good way to decide which state belongs to the screen and which belongs in the shared data layer.
g
you use compose right ? just put the logic in your main app composable/viewmodel
s
I can see why you’re trying the delegate here. The reusable part seems to include presentation behaviour as well as the use case, so sharing just the domain call wouldn’t remove all the repetition. I’d keep the delegate if it makes that behaviour easier to test and the screens easier to follow. The trade-off I’d watch is whether someone reading a ViewModel can still see which state and actions it exposes without having to chase through several delegates.