我在代码中使用回调流从 Firebase 数据库中检索数据。这是我的代码
@ExperimentalCoroutinesApi
suspend fun getUserOrder() = callbackFlow<UserOrder>{
println("Current Thread name is ${Thread.currentThread().name}")
databaseReference.child("Order").addValueEventListener(object : ValueEventListener{
override fun onCancelled(error: DatabaseError) {
Log.d("database error ",error.message)
channel.close(error.toException())
}
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
snapshot.children.forEach { data ->
data.children.forEach {newData->
newData.children.forEach { childData->
val userOrder = UserOrder(
childData.key!!,
childData.child("item_name").value as String,
childData.child("item_price").value as String,
childData.child("item_quantity").value as String,
childData.child("item_weight").value as String
)
offer(userOrder)
}
}
}
channel.close()
}
}
})
awaitClose()
}
//Activity class code
viewModel.viewModelScope.launch {
val time = measureTimeMillis {
viewModel.getOrder().collect {
println("Item id is ${it.item_id}")
}
}
println("Total time taken is $time")
}
数据正在检索,但它正在主线程上运行。我想在后台线程上运行它。这怎么可能?。告诉我任何人