我尝试运行两个异步作业。
有一个按钮,单击后会取消其中一项作业。但我注意到当我这样做时,其他工作也会被取消。
发生了什么?
class SplashFragment : BaseFragment(R.layout.fragment_splash), CoroutineScope by MainScope() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
launch {
val countdown = async { countDown() }
val ipAndMaintain = async { checkIPAndMaintain() }
btnSkip.onClick {
countdown.cancel() // cancel countdown
btnSkip.isVisible = false
if (!ipAndMaintain.isCompleted) {
showLoadingDialog()
}
}
countdown.await()
startOtherPage(ipAndMaintain.await())
}
}
private suspend fun countDown() {
var time = 3
while (time >= 0) {
btnSkip.text = getString(R.string.skip, time)
delay(1000)
yield()
time--
}
}
private suspend …
Run Code Online (Sandbox Code Playgroud)