Shiva s
Shiva s

Reputation: 897

How to upload multiple Images to Firebase Storage using Task function and get back the urls

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.

Upvotes: 1

Views: 339

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138944

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) //👈 Creates the UploadTask object.
    tasks.add(task)
}

Once you have the list full of UploasTask objects, then pass it to whenAllSuccess() method like this:

Tasks.whenAllSuccess<UploadTask>(tasks).addOnSuccessListener { uploadTasks ->
    val downloadUrls = mutableListOf<Uri>()
    uploadTasks.forEach {
        downloadUrls.add(it.await().storage.downloadUrl.await())
    }
    //Do what you need to do with the list.
}

Upvotes: 2

Related Questions