I want to upload multiple files in Firesbase and get back the URL when the upload is complete. I tried in a for loop uploading each one through and getting back the URLs and adding to a ArrayList
override suspend fun addProductImagesToFirebaseStorage(productImages: List<Uri>): AddProductImagesResponse {
return try {
val downloadUrls: MutableList<Uri> = arrayListOf()
for (item in productImages){
val productDownloadUrl = categoryImageStorage.reference.child("HomeFeed").child("Products")
.child("Product${UUID.randomUUID()}")
.putFile(item).await()
.storage.downloadUrl.await()
downloadUrls.add(productDownloadUrl)
}
Success(downloadUrls)
}catch (e:Exception){
Failure(e)
}
}
Is this is correct way to do it and want to know how to do it with Task<>whenAllSuccess
I tried using Task in this way please correct me with this method
override suspend fun addTestProductImagesToFirebase(testImages: List<Uri>): AddProductImagesResponse {
return try{
val downloadUrls: MutableList<Uri> = arrayListOf()
val taskArrayList: MutableList<Task<Uri>> = arrayListOf()
val task = testImages.forEach {
taskArrayList.add(
categoryImageStorage.reference.child("HomeFeed").child("Products")
.child("Product${UUID.randomUUID()}")
.putFile(it).await()
.storage.downloadUrl
)
}
Tasks.whenAll(taskArrayList).addOnSuccessListener {
downloadUrls.add(it)
}
Success(downloadUrls)
}catch (e:Exception){
Failure(e)
}
}
and want to know if uploading with the Tasks function is a more efficient way of doing it.
CodePudding user response:
You're almost there. To understand it better, I recommend you split the operations. First, you have to create a list of UploadTask objects:
val tasks = mutableListOf<UploadTask>()
productImages.forEach {
val task = categoryImageStorage.reference
.child("HomeFeed")
.child("Products")
.child("Product${UUID.randomUUID()}")
.putFile(it) //