Is `ViewModel` a thing of the past in the ages of ...
# multiplatform
j
Is
ViewModel
a thing of the past in the ages of Compose? I have this feeling because it came out so many years ago as a tool to work along with activities and fragments. Did it go under any changes when Google made it available for KMP? Was it ported to KMP so teams can share their code with minimal changes? I've been interested for a while in replacing
ViewModel
with something like
produceState
, but it falls short due to the limitations of
remember
. Circuit has a solution for that :
rememberRetained
but it uses
ViewModel
on Android behind the curtain to store the state value (Why not on all platforms since it's available on KMP actually?) Is it a trade off between "pure-compose" and not recreating a lot of stuff already implemented with
ViewModel
? Is it wrong to try not relying on all those old classes (ViewModel, ViewModelStore, ViewModelStoreOwner and ViewModelProvider) ?
e
IMO
ViewModel
(the Android architecture component, not MVVM) was a mistake that crept too deeply into the mainstream to simply disappear. I've successfully never used it. Maybe I'm biased, but all of my projects use https://github.com/eygraber/vice 😅
To expound on that, the main (only?) thing
ViewModel
solves is activity recreation. It isn't a full solution because it doesn't handle process death (that's what saved state is for), and eventually it just became the replacement god object for Activity / Fragment. Since you can never fully get rid of activity recreation (even with Compose and handling all config changes), you might still want to address the issue. The proper way to approach it is a combination of a modern architecture (which uses a UDF pattern) and saved state. Compose makes that easier to work with using
rememberSaveable
and there are lots of libraries offering MVVM or MVI architectures with UDF.
j
ViewModel also makes the mistake of being coupled to Android rather than allowing arbitrary objects to be passed through the non-config instance on activity recreation.
I tried to fix this in my last week at Google lol. I managed to land a change into the framework and was going to follow up with a change to androidx.activity for backwards compat, but it was decided to make it only exist in androidx.activity so we reverted the framework change... and then the week ran out.
😅 3
j
Right, I still wonder why ViewModel is used for the sole purpose of retaining data over activity recreation. Wouldn't it be better to just extract that part to an isolated component?
k
What kind of change on the framework side would be needed to mitigate that issue?
âž• 1