我在我的应用程序中使用Kotlin协同器,并选择了firebase作为数据库和存储的选择。在研究了firebase之后,我意识到它的所有API都是异步的,异步调用的结果在回调中返回,而去掉回调是我在应用程序中使用Kotlin协同器的主要原因。
这是我编写的将一个文件上传到防火墙云存储的代码,但是它给出了“任务尚未完成”的错误。
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的成功回调?
发布于 2019-08-20 08:42:47
kotlinx-coroutines-play-services 图书馆提供了允许等待任务完成的等待扩展函数,例如:
...
dependencies {
...
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1"
}return withContext(Dispatchers.IO) {
imageRef
.putFile(file)
.await() // await() instead of snapshot
.storage
.downloadUrl
.await() // await the url
.toString()
}https://stackoverflow.com/questions/57562864
复制相似问题