从 Runnable.run() 内部调用挂起函数

Calling a suspend function from inside Runnable.run()

我认为从概念上讲这应该可行。但是出现错误:

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

难道Java和Kotlin并行化不兼容?有解决办法吗?

其实我有Runnable只是为了通过它变成Handler:

handler.postDelayed(myRunnable, 100)

如果 Kotlin 中有类似的概念我可以使用,那也很好。

这不仅仅是 Java 和 Kotlin 并行兼容与否的问题。即使在纯 Kotlin 项目中,您也永远无法从协程或其他挂起函数外部调用挂起函数。挂起函数必须有一些协程入口点才能具有 CoroutineContext、CoroutineScope 和 Continuation,它们是协程工作的必要成分。

如果你想启动一个在延迟后做某事的协程,你可以使用 CoroutineScope 来启动一个协程,你可以调用 delay() 作为你在协程中做的第一件事。