我想使用协同程序依次运行三个功能。
private fun showAnimation() {
busy = true
mLog.i(TAG, "showing")
activity?.runOnUiThread {
button.text = ""
batchAnimation.visibility = View.VISIBLE
batchAnimation.playAnimation()
}
}
private fun hideAnimations(b: Boolean) {
busy = false
mLog.i(TAG, "hiding : $b ")
activity?.runOnUiThread {
button.text = "give feedback"
batchAnimation.visibility = View.GONE
batchAnimation.cancelAnimation()
}
}
suspend fun getBatchData(): Boolean {
var a = false
// network call that makes the value true when the needed data is returned else a remains false
return a
}
我给他们打电话如下
CoroutineScope(IO).launch {
showAnimation()
val a = async { getBatchData() }
hideAnimations(a.await())
}
无论如何调用hideanimations函数,而无需等待第二个函数的值
编辑:添加了getBatch函数
suspend fun getBatchData(): Boolean {
var a = false
// showAnimation()
launch {
context?.let {
val dao = MDatabase(it).getUserDao()
val trainerID = dao.getTrainerID()
mLog.i(TAG, "trainer id $trainerID")
json.put("trainer_id", trainerID)
NetworkOps.post(
Urls.batchUrl,
json.toString(),
context,
view!!.feedback,
object : response {
override fun onrespose(string: String?) {
mLog.i(TAG, "response $string")
val batches = Gson().fromJson(string, DCBatches::class.java)
if (batches.success == "1") {
val batchlist = batches.batches
if (batchlist.isNotEmpty()) {
mLog.i(TAG, "list length ${batchlist.size}")
launch {
context?.let { it ->
val dao1 = MDatabase(it).getBatchDao()
dao1.insertBatches(batchlist.toMutableList())
}
}
mLog.i(TAG, "inserted")
batchListSpinner.clear()
batchListSpinner.addAll(batchlist)
activity?.runOnUiThread {
batchAdapter.notifyDataSetChanged()
// hideAnimations()
}
} else {
showToast("Error no batches found")
// hideAnimations()
}
mLog.i(TAG,"setting true")
a = true
} else {
mLog.i(TAG, "error")
failedBatch()
}
}
override fun onfailure() {
failedBatch()
}
}) { _, _, _ ->
}
}
}
mLog.i(TAG,"returning value")
return a
}
我添加了两个日志语句,其中一个在将a
设置为true之后,另一个在最后返回值时设置。我可以看到该函数立即返回了布尔值,而无需等待api响应。我该如何解决??如何从回调中发送布尔值