Currently I have a main thread that constantly loops:
var suspension = Suspension()
fun loop() {
// Doing stuff here...
suspension.callTick()
// Doing more stuff here...
}
It calls the callTick() method which sends data to a channel:
class Suspension {
private val ticksChannel = Channel<Unit>(0)
fun callTick() {
ticksChannel.trySend(Unit)
}
suspend fun waitTick() {
ticksChannel.receive()
}
}
Now my last class makes use of this:
class Task(private val suspension: Suspension) {
suspend fun runTask() {
while (true) {
suspension.waitTick()
someMethodOnTheMainThread()
}
}
}
Now I'm wondering how I can call the someMethodOnTheMainThread() method from the main thread. The function has to be called right after the 'suspension.callTick()' method from loop(). At the moment I'm running the function from the coroutine thread. This causes a lot of errors and null pointer exceptions because it's not synchronized with the main thread.
Basically I'm wondering how to block / lock the main thread until the suspension.waitTick() method is called and the code after it is ran. Is this too complex? Is there another way to make suspending functions work with synchronized code?
Ok, so I have tried to implement my own dispatcher for the Client thread as follows:
It is practically the Swing dispatcher. Mainly I have changed the invokeLater method to my own implementation. Another noteworthy modification is that I use my own isEventDispatchThread implementation.
I am still using the Swing Timer class. I'm not sure if that's ok to do... But it seems to work from some testing.
For the invokeLater and isEventDispatchThread implementation:
Then in the loop method:
I now start the coroutine with: Dispatchers.Main. Which dispatcher is the main I've defined in the
resources/META-INF/services.kotlinx.coroutines.internal.MainDispatcherFactoryfile.