icerockdev / moko-mvvm

Model-View-ViewModel architecture components for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
1.02k stars 95 forks source link

iOS Livedata wrong observers call order #159

Closed Dorofeev closed 2 years ago

Dorofeev commented 2 years ago

code sample

val test = MutableLiveData("")

    fun bind1() {
        test.addObserver {
            println("first $it")

            if (it == "A") {
                test.value = "B"
            }
        }
    }

    fun bind2() {
        test.addObserver {
            println("second $it")
        }
    }

    fun start() {
        bind1()
        bind2()
        test.value = "A"
    }

After we call start function on iOS, in console we will see that observers calls in wrong order:

first A
first B
second B
second A

It happened because if we change value inside observer, changeValue function called recursively. For workaround we can call observers with storedValue, as below

    protected fun changeValue(value: T) {
        storedValue = value

        observers.forEach { it(storedValue) }
    }
Alex009 commented 2 years ago

will be available in 0.12.0