gpt4 book ai didi

android - Kotlin 协程 : Note: end time exceeds epoch:

转载 作者:行者123 更新时间:2023-11-29 23:30:31 24 4
gpt4 key购买 nike

结合 runBlockingwithContext 似乎可以发送消息注意:结束时间超过纪元:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
withContext(DefaultDispatcher) {
null
}
}
}
}

我使用了很多这样的协程并且 logcat 是垃圾邮件,有什么办法可以避免这种情况吗?另一种方法,例如:

var projects: List<ProjectEntity>? = runBlocking {
withContext(DefaultDispatcher) {
//Get the ProjectEntity list
}
}
projects?.let {
onResult(projects)
}

编辑

我根据您的评论尝试了一些方法(谢谢),但我无法得到与上面示例类似的结果:

Log.d("Coroutines", "getMostRecent start")
var localeProject: ProjectEntity? = null
launch {
withContext(CommonPool) {
Log.d("Coroutines", "getRecentLocaleProject")
localeProject = getRecentLocaleProject()
}
}
Log.d("Coroutines", "check localeProject")
if (localeProject != null) {
//Show UI
}

在 Logcat 中:

D/Coroutines: getMostRecent start
D/Coroutines: check localeProject
D/Coroutines: getRecentLocaleProject

我想把异步和同步的东西分开,没有这样的办法吗?我真的很想尽可能避免我的存储库中的所有回调。

最佳答案

Markos 的评论是正确的,您不应该阻塞 UI 线程。

您应该使用 launchasync 并使用 withContext 切换回 UI 线程。

您可以在这里找到一些示例:https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy

class MainActivity : ScopedAppActivity() {

fun asyncShowData() = launch { // Is invoked in UI context with Activity's job as a parent
// actual implementation
}

suspend fun showIOData() {
val deferred = async(Dispatchers.IO) {
// impl
}
withContext(Dispatchers.Main) {
val data = deferred.await()
// Show data in UI
}
}
}

请注意,该示例使用了新的协程 API (>0.26.0),它重命名了 Dispatchers。所以 Dispatchers.Main 对应旧版本中的 UI

关于android - Kotlin 协程 : Note: end time exceeds epoch:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52775333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com