I'm trying to execute some code after calling collect
on a Flow<MyClass>
. I'm still kind of new to using Flows so I don't understand why the code after the function doesn't get called.
我如何使用流程:
incidentListener = FirebaseUtils.databaseReference
.child(AppConstants.FIREBASE_PATH_AS)
.child(id)
.listen<MyClass>() //This returns a Flow<MyClass?>?
How I consume the Flow:
private suspend fun myFun() {
viewmodel.getListener()?.collect { myClass->
//do something here
}
withContext(Dispatchers.Main) { updateUI() } //the code never reaches this part
}
How myFun()
is called:
CoroutineScope(Dispatchers.IO).launch {
myFun()
}
就我试图让它工作而言,我试图关闭协同程序上下文,但没有成功.我假设流的工作方式不同于常规的协同程序.
Update:
我正在使用这段代码通过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) }
}