rickclephas/KMP-ObservableViewModel

Deriving state from other state gives errors in SwiftUI

Closed this issue · 2 comments

Trying to get familiar with this library and Kotlin in general. I created this view model, but when I use it I get a lot of errors in the console when using it on iOS:

Publishing changes from within view updates is not allowed, this will cause undefined behavior.
open class CounterViewModel: ViewModel() {

    private val _count = MutableStateFlow<Long>(viewModelScope, 0)

    @NativeCoroutinesState
    val count: StateFlow<Long> get() = _count
        .asStateFlow()

    @NativeCoroutinesState
    val isMultipleOfThree: StateFlow<Boolean> get() = _count
        .map { it % 3L == 0L }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), false)
}
Text(vm.isMultipleOfThree ? "Can be divided by 3!" : "Not divisible by 3.")

What is the proper way to update the UI with the derived value isMultipleOfThree?

I also tried with .asStateFlow() instead of the .stateIn but that fails to compile with the error:

Unresolved reference. None of the following candidates is applicable because of a receiver type mismatch:
fun <T> MutableStateFlow<T>.asStateFlow(): StateFlow<T>

Ah, I see that it works much simpler:

    val isMultipleOfThree: Boolean get() {
        return _count.value % 3L == 0L
    }

Hi. Both versions should work fine.
The error message is likely caused by some code changing one of the state values in the SwiftUI view body.