kotlinparallel-processingkotlin-coroutinesrunnable

Calling a suspend function from inside Runnable.run()


I think conceptually this should work. But there is an error:

Suspend function 'dueWorkingHours' should be called only from a coroutine or another suspend function

Is Java and Kotlin parallelization not compatible? Is there a way around this?

Actually, I have the Runnable only to throw it into a Handler:

handler.postDelayed(myRunnable, 100)

If there is a similar concept in Kotlin that I could use instead that would be fine too.


Solution

  • It’s not just a matter of Java and Kotlin parallelism being compatible or not. Even in pure Kotlin projects, you can never call suspend functions from outside a coroutine or other suspend function. There has to be some coroutine entry point for the suspend function to have a CoroutineContext, CoroutineScope, and Continuation, which are necessary ingredients for coroutines to work.

    If you want to start a coroutine that does something after a delay, you use a CoroutineScope to launch a coroutine and you can call delay() as the first thing you do in that coroutine.