Description
As your sample, we want to share the viewmodel on SwiftUI and Compose.
But there is a big difference between them, it's how a viewmodel is initialised, used and destroyed.
On SwiftUI, for exemple, the struct containing the view definition is initialised even the view is not displayed, as intended on SwiftUI with navigationLink, a good exemple is a list containing for each item a navigation link to a view containing a viewmodel.
So we can't put heavy code in the viewmodel constructor because it can be useless or cause memory waste, like data preloading or listener...
It's not the case on Compose, the viewmodel is initialised when the view will be displayed.
Currently, viewmodel data are loaded when it's bound/subscribed to the view.
Because of SharingStarted.Lazily
,
val allPlayers = repository.getPlayers()
.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
We can share logic between SwiftUI and Compose, but the lifecycle is clearly different; the constructor
and the fun onCleared()
don't have the same meaning.
I found some dirty solutions that could work, but no proper solution.
Let's talk about it