@@ -5,6 +5,8 @@ import androidx.lifecycle.ViewModel
55import androidx.lifecycle.viewModelScope
66import app.cash.molecule.RecompositionMode.Immediate
77import app.cash.molecule.launchMolecule
8+ import kotlinx.coroutines.CoroutineScope
9+ import kotlinx.coroutines.Dispatchers
810import kotlinx.coroutines.flow.MutableSharedFlow
911import kotlinx.coroutines.flow.SharedFlow
1012import kotlinx.coroutines.flow.SharingStarted
@@ -15,6 +17,8 @@ import kotlinx.coroutines.launch
1517
1618abstract class MoleculeViewModel <Event , Model > : ViewModel () {
1719
20+ val scope: CoroutineScope = CoroutineScope (viewModelScope.coroutineContext + Dispatchers .Main )
21+
1822 protected abstract val initialState: Model
1923
2024 // Events have a capacity large enough to handle simultaneous UI events, but
@@ -23,10 +27,10 @@ abstract class MoleculeViewModel<Event, Model> : ViewModel() {
2327
2428 // TODO: the model is only active when state is collected. This also means that events will not be collected either.
2529 val models: StateFlow <Model > by lazy {
26- viewModelScope .launchMolecule(mode = Immediate ) {
30+ scope .launchMolecule(mode = Immediate ) {
2731 models(events)
2832 }.onEach(::onSaveState)
29- .stateIn(viewModelScope , SharingStarted .Lazily , initialState)
33+ .stateIn(scope , SharingStarted .Lazily , initialState)
3034 }
3135
3236 fun take (event : Event ) {
0 commit comments