Par*_*dam 6 android kotlin firebase kotlin-coroutines
我在我的应用程序中使用 Kotlin 协程,并选择了 firebase 作为我的数据库和存储选择。在探索 firebase 之后,我意识到它的所有 API 都是异步的,并且异步调用的结果在回调中返回,而摆脱回调是我在我的应用程序中使用 Kotlin 协程的主要原因。
这是我编写的将文件上传到 firebase 云存储的代码,但它给出了“任务尚未完成”错误。
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()
}
}
Run Code Online (Sandbox Code Playgroud)
E/AndroidRuntime:致命异常:主进程:pk.com.kotlinapp,PID:7491 java.lang.IllegalStateException:com.google.android.gms.common.internal.Preconditions.checkState(未知来源)处的任务尚未完成在 com.google.android.gms.tasks.zzu.zzb(未知来源)在 com.google.android.gms.tasks.zzu.getResult(未知来源)在 prk.com.kotlinapptest.DatabaseManager$saveImage$2.invokeSuspend( DatabaseManager.kt:28) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241) at kotlinx.coroutines.scheduling.CoroutineSafelyScheduler. (CoroutineScheduler.kt:594) 在 kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60) 在 kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)
有什么方法可以将文件上传到 firebase 云存储并获取下载 URL,而无需在成功回调中获取下载 URL?
kotlinx-coroutines-play-services
库提供了await扩展功能,允许等待任务完成,如:
...
dependencies {
...
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1"
}
Run Code Online (Sandbox Code Playgroud)
return withContext(Dispatchers.IO) {
imageRef
.putFile(file)
.await() // await() instead of snapshot
.storage
.downloadUrl
.await() // await the url
.toString()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2087 次 |
最近记录: |