https://kotlinlang.org logo
Title
b

benkuly

03/03/2023, 7:35 AM
I get the following exception in my tests after upgrading decompose to 1.0.0:
Access from different threads is detected, must be on the main thread only.Current thread: AWT-EventQueue-0 @coroutine#5082. First thread: AWT-EventQueue-0 @coroutine#11.
Thown here:
withContext(Dispatchers.Main.immediate) {
    push(configuration, onComplete) // <--
}
Any idea what's the problem?
a

Arkadii Ivanov

03/03/2023, 8:31 AM
Most likely you created the root component on non-UI thread. Try following https://arkivanov.github.io/Decompose/component/overview/#jvmdesktop-with-compose
If this is already what you are doing, or the problem is still there. Try adding the following at the very beginning of your application: fun main() { runOnUiThread { val value = MutableValue(0) value.value = 1 } // The rest of the code } This will remember the correct thread, and all subsequent violations should throw proper stack traces.
b

benkuly

03/03/2023, 8:38 AM
Hm okay. This does not work:
withContext(Dispatchers.Main.immediate)
Notice: It is common test-code. Therefore only a few view models are created...
a

Arkadii Ivanov

03/03/2023, 8:39 AM
Ahh, this is in tests. I missed that.
Could you post your test here?
b

benkuly

03/03/2023, 8:41 AM
I can try creating a minimal reproducer.
a

Arkadii Ivanov

03/03/2023, 8:42 AM
That would be very helpful
The problem may be that you are using the real main dispatcher in tests. This may trigger the check. And this also makes your tests asynchronous. You can pass all used dispatchers via constructor (with default values) and replace them in tests. E.g. with StandardTestDispatcher or UnconfinedDispatcher. I will add an API to disable main thread checks in the next version, just in case one still wants to use real Dispatchers.
e

Evegenii Khokhlov

03/03/2023, 9:20 AM
Also
kotlinx-coroutines-test
has very handy
Dispatchers.setMain()
method.
a

Arkadii Ivanov

03/03/2023, 9:21 AM
Yes, this can be also used. Here are some docs (Android, but still can be useful) - https://developer.android.com/kotlin/coroutines/test#setting-main-dispatcher
b

benkuly

03/03/2023, 9:26 AM
Setting
Dispatchers.setMain()
and don't using real main dispatchers was the trick. Thank you 🙂