gpt4 book ai didi

android - Anko doAsyncResult 协程

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:02 24 4
gpt4 key购买 nike

我是 anko 和协程的新手,所以如果我问一些琐碎的事情,请原谅 :)

所以我想要做的是让用户点击一个按钮,然后我想从互联网上下载一个 JSON,将它存储在本地并解析它。由于这两个操作都需要相当长的时间,所以我考虑使用 anko 协程。

所以第一个问题是:

<强>1。我可以使用嵌套的 doAsync 调用,在第一个 UIThread 中调用第二个 doAsync 吗?我试过了,它似乎有效,但感觉不对,所以我试图找到一种更优雅的方式

例子:

doAsync {
downloadFileFromUrl(fileUrl)

uiThread {
doAsync {
IOUtils.parseFile(context!!)
val database = AppDatabase.getInstance(context!!)
val results = database.resultsDao().all

uiThread {
//show Results
}
}
}
}

<强>2。在为我的问题寻找解决方案时,我发现了 doAsyncResult。如果 1 不正确,这是正确的方法吗?我已经尝试过使用它,但使用 bool 值时出现错误。见下文:

    private fun downloadFileFromUrl(fileUrl: String): Boolean {

try{
//Download file. No doAsync calls here.
//The procedure just returns true if successful or false in case of any errors

return true
} catch (e: Exception) {
Log.e("Error: ", e.message)
return false
}
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
parseButton.setOnClickListener {
try {
val downloadFileResult: (AnkoAsyncContext<Boolean>.() -> Boolean) = {
::downloadFileFromUrl.invoke(fileUrl)
}

val downloadFileResultFutureValue: Future<Boolean> = doAsyncResult(null, downloadFileResult)

//Continue processing if downloadFileResultFutureValue is true
} catch (e: IOException) {
e.printStackTrace()
}
}
}

这一行

val downloadFileResultFutureValue: Future<Boolean> = doAsyncResult(null, downloadFileResult)

编译时出现以下错误,我不知道如何修复:

Type inference failed: Cannot infer type parameter T in 

fun <T, R> T.doAsyncResult
(
exceptionHandler: ((Throwable) → Unit)? = ...,
task: AnkoAsyncContext<T>.() → R
)
: Future<R>
None of the following substitutions

receiver: Boolean
arguments:
(
((Throwable) → Unit)?,
AnkoAsyncContext<Boolean>.() → Boolean
)

receiver: BlankFragment
arguments:
(
((Throwable) → Unit)?,
AnkoAsyncContext<BlankFragment>.() → Boolean
)
can be applied to

receiver: BlankFragment
arguments:
(
Nothing?,
AnkoAsyncContext<Boolean>.() → Boolean
)

提前致谢

最佳答案

这样做:

doAsync {
// 1. Something
uiThread {
// 2. Nothing
doAsync {

确实没有多大意义,除非(2)不是什么都没有,而你只是省略了一些代码。
如果你没有,你可以继续使用这个版本:

doAsync {
downloadFileFromUrl(fileUrl)
IOUtils.parseFile(context!!)
val database = AppDatabase.getInstance(context!!)
val results = database.resultsDao().all

uiThread {
//show Results
}
}

由于 parseFile() 无论如何都依赖于 downloadFileFromUrl(),并且所有内容都在协程中运行,因此来回添加此操作并不会提高并发性.

关于android - Anko doAsyncResult 协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956326/

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