I'm aware that Kotlin/Native has very specific rules in regards to mutability of objects between threads.
However to my surprise, I've found that when running unit tests from commonMain (deployed to androidTestDebug), I am able to change mutable states on different threads. For example this works fine when changing the value in MyData
:
data class MyData(var value : Int = 0)
suspend fun main() = coroutineScope {
val myData = MyData()
val newContext1 = newSingleThreadContext("contextOne")
val newContext2 = newSingleThreadContext("contextTwo")
launch (newContext1) {
myData.value = 1
}
launch (newContext2) {
myData.value = 2
}
}
However if I run this while targeting iOS, it crashes, giving me kotlin.native.concurrent.InvalidMutabilityException
. This is what I would expect to happen on both platforms. I'm new to KMM, but why aren't concurrent mutability rules enforced when running commonMain code on JVM?
Also is there a way to force mutability rules on the JVM so that tests fail on Android just as they would on iOS? I think this would help ensure platform consistency.
No, it shouldn’t crash on Android.
Kotlin native creates Native code from Kotlin, that’s why there’s a need in it’s own concurrency model.
For android part this is plain kotlin code, so JVM concurrency model can be used, and as any other kotlin code that mutates a variable it shouldn’t crash.
I don’t think there’s a way to make it crash on Android.
In kotlin 1.6.0 this should be changed so this code is not gonna crash on both platforms