1

我在代码中使用回调流从 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")
    }

数据正在检索,但它正在主线程上运行。我想在后台线程上运行它。这怎么可能?。告诉我任何人

4

1 回答 1

2

您使用viewModelScope“绑定到Dispatchers.Main.immediate”的 启动协程。这就是你的协程在主线程中运行的原因。

要跳转线程,您可以使用withContext.

IO调度程序可用于线程阻塞调用,我在给定的代码中没有看到。

于 2020-06-28T17:19:09.377 回答