Anthony Pages
12/16/2020, 3:57 PM@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,
let flowTest = FlowAndCoroutines()
flowTest.observeOnMain {
print("Callback called")
}
// In MAIN thread
flowTest.triggerCollect() // output "Callback called"
// In another thread
flowTest.triggerCollect() // Throw exception IncorrectDereferenceException
Kris Wong
12/16/2020, 4:20 PMAnthony Pages
12/16/2020, 4:24 PMAnthony Pages
12/16/2020, 4:27 PMMainScope().async(Dispatchers.Main) { }
is different from this Swift code :
DispatchQueue.main.async { }
? why ?Kris Wong
12/16/2020, 4:27 PMcounter
, not on flowTest
Kris Wong
12/16/2020, 4:28 PMAnthony Pages
12/16/2020, 4:30 PMfreeze()
method but not on the Swift side.
Q2: yes ok, was thinking it was the same behavior behindKris Wong
12/16/2020, 4:31 PMinit
method, or add an API to freeze it.Anthony Pages
12/16/2020, 4:33 PMAnthony Pages
12/16/2020, 4:34 PMAnthony Pages
12/16/2020, 4:35 PMAnthony Pages
12/21/2020, 2:46 PMfreeze()
method in the init
works perfectly, Thx !