Skip to content

Commit 887da46

Browse files
committed
Fix issue with viewmodel slowing down composables
1 parent c495802 commit 887da46

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

composeApp/src/commonMain/kotlin/io/middlepoint/morestuff/shared/ui/MoleculeViewModel.kt

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import androidx.lifecycle.ViewModel
55
import androidx.lifecycle.viewModelScope
66
import app.cash.molecule.RecompositionMode.Immediate
77
import app.cash.molecule.launchMolecule
8+
import kotlinx.coroutines.CoroutineScope
9+
import kotlinx.coroutines.Dispatchers
810
import kotlinx.coroutines.flow.MutableSharedFlow
911
import kotlinx.coroutines.flow.SharedFlow
1012
import kotlinx.coroutines.flow.SharingStarted
@@ -15,6 +17,8 @@ import kotlinx.coroutines.launch
1517

1618
abstract 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

Comments
 (0)