在调用collect
后,我尝试在Flow<MyClass>
上执行一些代码。对于使用流,我还是有点陌生,所以我不明白为什么函数之后的代码没有被调用。
我是如何使用流程的:
incidentListener = FirebaseUtils.databaseReference
.child(AppConstants.FIREBASE_PATH_AS)
.child(id)
.listen<MyClass>() //This returns a Flow<MyClass?>?
我是如何消耗流程的:
private suspend fun myFun() {
viewmodel.getListener()?.collect { myClass->
//do something here
}
withContext(Dispatchers.Main) { updateUI() } //the code never reaches this part
}
如何调用myFun()
:
CoroutineScope(Dispatchers.IO).launch {
myFun()
}
至于我想让它起作用的东西,我试着关闭协同线上下文,但它没有起作用。我假设流的工作方式与常规协同机制不同。
更新:
我正在使用这个代码块通过Firebase监听。我不知道它是否有帮助,但也许是我实现它的方式引起了问题?
inline fun <reified T> Query.listen(): Flow<T?>? =
callbackFlow {
val valueListener = object : ValueEventListener {
override fun onCancelled(databaseError: DatabaseError) {
close()
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
try {
val value = dataSnapshot.getValue(T::class.java)
offer(value)
} catch (exp: Exception) {
if (!isClosedForSend) offer(null)
}
}
}
addValueEventListener(valueListener)
awaitClose { removeEventListener(valueListener) }
}
发布于 2020-03-19 17:54:59
collect
是一个挂起函数,collect
之后的代码将只在流完成后运行。
在一个单独的协同线中启动:
private suspend fun myFun() {
coroutineScope {
launch {
viewmodel.getListener()?.collect { myClass->
//do something here
}
}
withContext(Dispatchers.Main) { updateUI() } //the code never reaches this part
}
}
https://stackoverflow.com/questions/60761812
复制相似问题