【发布时间】:2020-01-16 10:07:20
【问题描述】:
我是协程新手。这是一个普遍的问题。我已经研究过其他问题,但它们更针对特定用例。
目前,我正在使用以下基于回调的架构:
class MyService: Service(), OnComplete {
...
companion object {
lateinit var serviceContext: Context
}
...
override fun onCreate() {
super.onCreate()
serviceContext = this
}
...
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
MyAsyncTask().execute() // start the background job
return super.onStartCommand(intent, flags, startId)
}
...
override fun onCompleteFunc(resultBundle: Bundle) {
// do something when the job is finished
}
}
AsyncTask如下:
class MyAsyncTask: AsyncTask<Any, Any, Any>() {
...
val onComplete by lazy { MyService.serviceContext as OnComplete }
...
override fun doInBackground(vararg params: Any?): Any {
// do the background job here
// store the results somewhere
return 0
}
...
override fun onPostExecute(result: Any?) {
super.onPostExecute(result)
onComplete.onCompleteFunc( // job finished. send the results
Bundle().apply {
// put extras here
}
)
}
}
还有界面:
interface OnComplete {
fun onCompleteFunc(resultBundle: Bundle)
}
我对迁移到 kotlin 协程非常感兴趣。请帮我解决这个问题。
问候, 赛扬坦
【问题讨论】:
-
你可以从 codelab 开始:codelabs.developers.google.com/codelabs/kotlin-coroutines/#0
-
请不要因为他们的英语不完美而对别人发火,尤其是当他们努力保持礼貌时。阻碍他们的是他们不知道如何进行。呃。在这种情况下,有用的链接可能会很有帮助。 (codelabs 可以帮助您理解协程,但无助于将 AsyncTask 转换为协程;这不是他们教程的一部分。)
标签: android android-asynctask kotlin-coroutines