首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Firebase与Kotlin协同

用Firebase与Kotlin协同
EN

Stack Overflow用户
提问于 2019-08-19 19:29:43
回答 1查看 3.4K关注 0票数 7

我在我的应用程序中使用Kotlin协同器,并选择了firebase作为数据库和存储的选择。在研究了firebase之后,我意识到它的所有API都是异步的,异步调用的结果在回调中返回,而去掉回调是我在应用程序中使用Kotlin协同器的主要原因。

这是我编写的将一个文件上传到防火墙云存储的代码,但是它给出了“任务尚未完成”的错误。

代码语言:javascript
复制
private suspend fun saveImage(filePath: String): String? {
        val storage = FirebaseStorage.getInstance("gs://myapp-9a648.appspot.com/")
        val storageRef = storage.reference
        val file = Uri.fromFile(File(filePath))
        val imageRef = storageRef.child("images/${file.lastPathSegment}")
        return withContext(Dispatchers.IO) {
            imageRef.putFile(file).snapshot.storage.downloadUrl.result.toString()
        }
    }

E/AndroidRuntime:致命异常:主要进程: pk.com.kotlinapp,PID: 7491 java.lang.IllegalStateException:任务尚未在com.google.android.gms.tasks.zzu.getResult(Unknown源代码的com.google.android.gms.tasks.zzu.zzb(未知源)的com.google.android.gms.tasks.zzu.zzb上完成,任务在kotlin.coroutines的prk.com.kotlinapptest.DatabaseManager$saveImage$2.invokeSuspend(DatabaseManager.kt:28)上完成.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241) at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594) at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)

有什么办法可以上传一个文件到firebase云存储,并获得下载的URL,而不获得下载URL的成功回调?

EN

回答 1

Stack Overflow用户

发布于 2019-08-20 08:42:47

kotlinx-coroutines-play-services 图书馆提供了允许等待任务完成的等待扩展函数,例如:

代码语言:javascript
复制
...
dependencies {
  ...
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1"
}
代码语言:javascript
复制
return withContext(Dispatchers.IO) {
    imageRef
        .putFile(file)
        .await() // await() instead of snapshot
        .storage
        .downloadUrl
        .await() // await the url
        .toString()
}
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57562864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档