【发布时间】:2019-12-25 12:39:24
【问题描述】:
我有这个静态(伴随对象)函数来从 Firebase Firestore 下载事件信息和从 Firebase Storage 下载事件图像:
fun downloadEventInformationAndImages() {
FirebaseFirestore.getInstance().collection("events").document(downloadedEventID)
.get().addOnSuccessListener { snap ->
//Download Event Information Here
//Do stuff
GlobalScope.launch(Dispatchers.Main) {
//Download Event Images Here
val downloadEventImage = FirebaseStorage.getInstance().reference.child("Images/Events/$eventID/eventPhoto.jpeg")
.getBytes(1024 * 1024).asDeferred()
val downloadEventFounderImage = FirebaseStorage.getInstance().reference.child("Images/Users/$founderID/profilePhoto.jpeg")
.getBytes(1024 * 1024).asDeferred()
try {
val downloadedImages = mutableListOf<ByteArray>(
downloadEventImage.await(),
downloadEventFounderImage.await())
// Update stuff on UI
} catch(e: StorageException) {
// Error handling
}
}.addOnFailureListener { exception ->
// Error handling
}
}
}
我想要做的是避免使用 GlobalScope,但是当我尝试将 runBlocking 添加到 downloadEventInformationAndImages() 时:
fun downloadEventInformationAndImages() = runBlocking {
// Do stuff
launch(Dispatchers.Main) {
它不起作用(它没有等待 Firebase 完成下载 - 然后我将 runBlocking 移到函数内部,也不起作用)。如何避免使用 GlobalScope?提前致谢。
【问题讨论】:
-
你不能只传递与调用者生命周期相关的
CoroutineScope作为downloadEventInformationAndImages的参数吗? -
嘿@RicardoCosteira!它有效 - 我很惊讶答案如此简单 - 谢谢! :) 由于我是 Kotlin 和 Coroutines 的新手,在传递 CoroutineScope 作为参数(例如内存泄漏等)时我应该注意哪些具体事项?
-
很高兴它成功了 :) 我会在几分钟内写出更详细的答案。
标签: firebase kotlin google-cloud-firestore firebase-storage