我在我的代码中使用回调流程从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")
}
正在检索数据,但它正在主线程上运行。我想在后台线程上运行它。这怎么可能?。告诉我任何人
答案 0 :(得分:0)
您用viewModelScope
(它绑定到{% block page_script %}
<script>
var $list = $("form :input[type='text']");
$list.each(function () {
$(this).addClass("form-control");
});
var $select = $("form select");
$select.each(function () {
$(this).addClass("custom-select w-90");
});
var $select = $("form textarea");
$select.each(function () {
$(this).addClass("form-control");
});
var $list = $("form :input[type='number']");
$list.each(function () {
$(this).addClass("form-control");
});
)启动了协程。
这就是您的协程在主线程中运行的原因。
要跳转线程,可以使用withContext
。
IO
dispatcher可用于线程阻塞调用,我在给定的代码中看不到。