[英]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 Suspend function 'dueWorkingHours' 只能从协程或另一个 suspend function 调用
Is Java and Kotlin parallelization not compatible? Java和Kotlin并行不兼容? Is there a way around this?有没有解决的办法?
Actually, I have the Runnable
only to through it into a Handler
:实际上,我只有Runnable
才能通过它进入Handler
:
handler.postDelayed(myRunnable, 100)
If there is a similar concept in Kotlin that I could use instead that would be fine too.如果 Kotlin 中有类似的概念,我可以用它来代替,那也很好。
It's not just a matter of Java and Kotlin parallelism being compatible or not.这不仅仅是 Java 和 Kotlin 并行性是否兼容的问题。 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.即使在纯 Kotlin 项目中,您也永远不能从协程或其他挂起 function 外部调用挂起函数。挂起 function 必须有一些协程入口点才能拥有 CoroutineContext、CoroutineScope 和 Continuation,这些是协程的必要成分工作。
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.如果你想启动一个在延迟后做某事的协程,你可以使用 CoroutineScope 来启动一个协程,你可以调用delay()
作为你在该协程中做的第一件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.