Michael Ferguson
1 min readDec 29, 2021

--

Rather than reimplementing all the android framework things that create and restore view models why not just create a view model delegate that the android view model proxies to?

To me it seems strange to complain about having to use an android view model only have to have rebuild the entire android toolchain needed to preserve view models. Why not just use what's there and delegate to a non-android view model instead? Then, when not within the android framework you can create your delegate view model however you like and use the "real" view model directly.

Eg something like:

interface MyMultiPlatformViewModelInterface {
fun doAThing()
}

class MyMultiPlatformViewModel @Inject constructor(
private val scope: CoroutineScope
) : MyMultiPlatformViewModelInterface, CoroutineScope by scope {
override fun doAThing() {}
}

class MyAndroidViewModel @AssistedInject constructor(
private val realViewModel: MyMultiPlatformViewModel,
@Assisted private val savedStateHandle: SavedStateHandle,
): ViewModel(), MyMultiPlatformViewModelInterface by realViewModel {

init {
// apply saved state to the multiplatform view model
}

override fun onCleared() {
super.onCleared()
// maybe call the delegates cleared?
}
}

--

--

Michael Ferguson
Michael Ferguson

Written by Michael Ferguson

Android software developer. Views and opinions expressed are my own and not that of my employer.

Responses (1)