Hi there! I trying to dig into Kotlin MPP and cor...
# kotlin-native
a
Hi there! I trying to dig into Kotlin MPP and coroutines, especially on iOS, but I don’t understand something. I have the following class in my Kotlin Library :
Copy code
@ThreadLocal
var counter = MutableStateFlow(0)

class FlowAndCoroutines {
    fun observeOnMain(callback: () -> Unit){
        MainScope().async(Dispatchers.Main) {
            counter.collect {value ->
                callback()
            }
        }
    }

    fun triggerCollect() {
        MainScope().async(Dispatchers.Main) {
            counter.emit(counter.value + 1)
        }
    }
}
Now on iOS,
Copy code
let flowTest = FlowAndCoroutines()

flowTest.observeOnMain {
    print("Callback called")
}

// In MAIN thread
flowTest.triggerCollect() // output "Callback called"

// In another thread 
flowTest.triggerCollect() // Throw exception IncorrectDereferenceException
k
you can't instantiate an object on one thread and reference it on another, unless it's frozen
a
Yes, I have seen this but was thinking that the @ThreadLocal will help me
And the other thing I do not understand is this kotlin code :
Copy code
MainScope().async(Dispatchers.Main) { }
is different from this Swift code :
Copy code
DispatchQueue.main.async { }
? why ?
k
you have @ThreadLocal on
counter
, not on
flowTest
as for your second question, 1 is using coroutines (Kotlin), and the other is using GCD (platform)
a
Q1: Ok, then how could I have a frozen instance ? I have seen that I could use
freeze()
method but not on the Swift side. Q2: yes ok, was thinking it was the same behavior behind
k
either have the object freeze itself in the
init
method, or add an API to freeze it.
a
Didn’t have the freeze method neither on the kotlin side. Am I missing something ? Did you have any documentation or link to share ?
(nvm I found it in the specific platform code)
Thank you very much, I will try that way.
🍻 1
Edit: The
freeze()
method in the
init
works perfectly, Thx !