我正在尝试将图像上传到 Firebase Storage,返回包含下载网址的 Flow。 问题是,显然 onCompleteListener 中的 this 与回调流中的 this 不同。 很难描述,但我认为代码会让问题变得清楚。
fun uploadImage(eventId: String, imageUri: String) : Flow<String> = callbackFlow {
val uri = imageUri.toUri()
val storageRef = storage.reference
val imageRef = storageRef.child(eventId).child("large.jpg")
val uploadTask = imageRef.putFile(uri)
val returnFlow = this
uploadTask.continueWithTask {task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
imageRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
// this.trySend here doesn't go outside and the collect never triggers
// storing the outer this in a variable like in returnFlow doesn't work either
task.let { returnFlow.trySend(task.result.toString()).isSuccess }
} else {
// Handle failures
// ...
}
}
// this.trySend here works
this.trySend("")
awaitClose()
}
该函数在这里调用:
class AddEvent(private val repository: Repository) {
suspend operator fun invoke(
imageUri : String
) {
val uuid = UUID.randomUUID().toString()
repository.uploadImage(uuid, imageUri).collect{
// Do something with the image url
}
}
}
我确实遇到了同样的问题。
我不只是使用
trySend
,而是使用 channel.trySend
,效果很好。
channel
位于channelFlow上下文中。