【发布时间】:2021-09-13 22:15:27
【问题描述】:
我正在查看 Android 开发者网站上的流程文档,我有一个问题。
https://developer.android.com/kotlin/flow#callback
如果你查看上面的链接,你会看到这样的代码。
class FirestoreUserEventsDataSource(
private val firestore: FirebaseFirestore
) {
// Method to get user events from the Firestore database
fun getUserEvents(): Flow<UserEvents> = callbackFlow {
// Reference to use in Firestore
var eventsCollection: CollectionReference? = null
try {
eventsCollection = FirebaseFirestore.getInstance()
.collection("collection")
.document("app")
} catch (e: Throwable) {
// If Firebase cannot be initialized, close the stream of data
// flow consumers will stop collecting and the coroutine will resume
close(e)
}
// Registers callback to firestore, which will be called on new events
val subscription = eventsCollection?.addSnapshotListener { snapshot, _ ->
if (snapshot == null) { return@addSnapshotListener }
// Sends events to the flow! Consumers will get the new events
try {
offer(snapshot.getEvents())
} catch (e: Throwable) {
// Event couldn't be sent to the flow
}
}
// The callback inside awaitClose will be executed when the flow is
// either closed or cancelled.
// In this case, remove the callback from Firestore
awaitClose { subscription?.remove() }
}
}
在上面的代码中,awaitClose被解释为在协程关闭或取消时执行。
但是,除了初始化eventsCollection的try-catch语句之外,代码中没有close()。
另外,在 Android 开发者页面底部显示offer does not add the element to the channel and **returns false** immediately。
我的问题是,在上面的代码中,当offer(snapshot.getEvents())被执行时,协程是不是用return false取消,所以awaitClose被执行了?
【问题讨论】:
-
Offer已弃用,应更改为trySend -
@Andrew 谢谢你告诉我!那么,
trySend取消与return false的协程是否正确?