简体   繁体   English

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

[英]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.

相关问题 在 retrofit onResponse 方法中运行 suspend function - Run suspend function inside retrofit onResponse method 父挂起函数中的这些挂起函数会按顺序运行吗? - Will these suspend functions inside in a parent suspend function be run in sequence? 协程中的非挂起函数是否仍然在另一个线程上运行? - Does a non suspend function inside a coroutine still run on another thread? 从活动中调用协程 function 返回`应该只从协程或另一个挂起函数调用` - calling coroutine function from activity returns `should be called only from a coroutine or another suspend function` 如何阻止正在调用 firebase 的挂起 function - How to block a suspend function that is calling firebase 如何在不等待结果的情况下在另一个内部运行挂起功能? - How to run a suspend function inside another one without waiting for its result? 在 Iterable.sortedBy 中执行暂停 function - Executing suspend function inside Iterable.sortedBy 挂起函数中的阻塞与调用异步函数有何不同? - How is blocking in a suspend function different than calling an async function? 如何从函数调用挂起函数 - How to Call Suspend Function from Function 如何从kotlin的构造函数内的匿名挂起函数访问类方法? - How to access class methods from anonymous suspend function inside constructor in kotlin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM