我正在尝试将多个文件上传到Firebase,并希望在所有上传任务完成后将其链接到另一个孩子。为了达到这个目的,我试图在kotlin中使用协程。下面是代码(如果我错了,请改正我,因为我在协程中确实很糟糕):
fun create(placemark: PlacemarkModel,callback: () -> Unit=fun(){})=runBlocking {
val key = db.child("users").child(userId).child("placemarks").push().key
placemark.id = key!!
placemarks.add(placemark)
db.child("users").child(userId).child("placemarks").child(key).setValue(placemark)
uploadImage(placemark.dp,"dp",placemark)
if (placemark.images.size>0){
placemark.images.forEach{
uploadImage(it,"images",placemark,placemark.images.indexOf(it))
}
}
这是我的uploadImage
函数,我打算等待它完成运行并将URI传递回主函数
suspend fun uploadImage(image:String,
type:String,
placemark: PlacemarkModel,
index:Int=0,
callback:()->Unit=fun(){}):URI{
st = FirebaseStorage.getInstance().reference
info("Coroutines 2")
val imageRef = st?.child(userId + '/' + File(image).name)
val data=readAndCompress(image)
data?.let {
var uploadTask=imageRef?.putBytes(data)
uploadTask?.addOnFailureListener {
println(it.message)
}?.addOnSuccessListener { taskSnapshot ->
//I want to return the URI here however return is not allowed
}
}
}
谢谢您的时间。
答案 0 :(得分:0)
事实证明,我可以将所有任务添加到任务列表并调用
Tasks.whenAllSuccess(tasks).addCompleteListener {//在此处回调}