gpt4 book ai didi

android - Kotlin等待与协程异步

转载 作者:行者123 更新时间:2023-12-02 13:15:28 24 4
gpt4 key购买 nike

我想在实例化phoneViewModel和ScanViewModel时打开一个新 Activity 。通过调用异步函数InitialRead()实例化它们。我正在记录每个步骤,它们被记录为done3 => done2 => done1
我想按以下顺序排列它们:
done1 => done2 => done3
我有以下代码:

class MainBusinessActivity : AppCompatActivity() {

private lateinit var scanViewModel: ScanViewModel
private lateinit var phoneViewModel: PhoneViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_business)
}

private fun startEntitySetListActivity() = GlobalScope.async {
val sapServiceManager = (application as SAPWizardApplication).sapServiceManager
sapServiceManager?.openODataStore {
phoneViewModel = ViewModelProvider(this@MainBusinessActivity).get(PhoneViewModel::class.java).also {it.initialRead{Log.e("done", "done1")}}
scanViewModel = ViewModelProvider(this@MainBusinessActivity).get(ScanViewModel::class.java).also {it.initialRead{Log.e("done", "done2")}}
}
}

override fun onResume() {
super.onResume()
//startEntitySetListActivity()
runBlocking {
startEntitySetListActivity().await()
val intent = Intent(this@MainBusinessActivity, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
Log.e("done", "done3")
startActivity(intent)
}
}
}
我究竟做错了什么?有人可以更正我的代码吗?

最佳答案

请勿在Android应用中使用runBlockingrunBlocking完全违反了使用协程的目的,并可能导致ANR。您也可能永远不要使用GlobalScope,这会导致UI泄漏。您可能需要它来执行某种长时间运行的任务,该任务对于放入服务没有意义,但不依赖于任何UI组件,但是我想不到任何示例
您也不应在后台实例化ViewModel。那应该在onCreate()中完成。
将此函数设为暂停函数,它可以在返回之前同时在后台分解两个任务。
lifecycleScope开始协程。
假设sapServiceManager?.openODataStore是需要回调的异步任务,则需要将其包装在suspendCoroutine中。

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_business)
phoneViewModel = ViewModelProvider(this@MainBusinessActivity).get(PhoneViewModel::class.java)
scanViewModel = ViewModelProvider(this@MainBusinessActivity).get(ScanViewModel::class.java)
}

private suspend fun startEntitySetListActivity() = coroutineScope {
val sapServiceManager = (application as SAPWizardApplication).sapServiceManager
sapServiceManager ?: return
suspendCoroutine<Unit> { continuation ->
sapServiceManager.openODataStore { continuation.resume(Unit) }
}
listOf(
launch {
phoneViewModel.initialRead{Log.e("done", "done1")}
},
launch {
scanViewModel.initialRead{Log.e("done", "done2")}
}
).joinAll()
}

override fun onResume() {
super.onResume()
lifecycleScope.launch {
startEntitySetListActivity()
val intent = Intent(this@MainBusinessActivity, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
Log.e("done", "done3")
startActivity(intent)
}
}

关于android - Kotlin等待与协程异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64469210/

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