kotlin 我无法在addOnSuccessListener中迭代UploadTask

oknrviil  于 2023-01-21  发布在  Kotlin
关注(0)|答案(1)|浏览(120)

我在尝试迭代addOnSuccessListener方法中的uploadTasks时遇到以下错误。
java.lang.ClassCastException:上传任务$任务快照不能转换为上传任务
那么我怎样才能得到addOnSuccessListener中每个Img的下载字符串呢?

val baos = ByteArrayOutputStream()
val tasks = mutableListOf<UploadTask>()

listImg.forEach {
        if(bitmap!!.byteCount != it.byteCount) {
            val bitmap = it
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            val data = baos.toByteArray()
            var uploadTask = spaceRef.putBytes(data)

            tasks.add(uploadTask)
        }
    }

Tasks.whenAllSuccess<UploadTask>(tasks).addOnSuccessListener { uploadTasks ->
        //uploadTasks has size of 2
        val urls = mutableListOf<Uri>()
        
        lifecycleScope.launch
        {
            //Error throws here
            uploadTasks.forEach{

            urls.add(it.await().storage.downloadUrl.await())
        }

     }
 }
plicqrtu

plicqrtu1#

whenAllSuccess的类型是<TResult>,所以应该使用结果类型UploadTaskUploadTask.TaskSnapshot):

Tasks.whenAllSuccess<UploadTask.TaskSnapshot>(tasks).addOnSuccessListener { uploadTasks ->

然后可以将第一个await()放到最后一行:

urls.add(it.storage.downloadUrl.await())
奖金:不要阻塞主线程

注意Tasks.whenAllSuccess()会阻塞主线程直到所有上传成功,这意味着上传文件时UI可能会冻结。为了避免这种情况,请考虑使用Coroutines上传文件:

val baos = ByteArrayOutputStream()
val urls = mutableListOf<Uri>()

lifecycleScope.launch {
    listImg.forEach {
        if(bitmap!!.byteCount != it.byteCount) {
            val bitmap = it
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            val data = baos.toByteArray()

            // Upload the image first
            val taskSnapshot = spaceRef.putBytes(data).await()
            // Get the download Url
            val downloadUri = taskSnapshot.storage.downloadUrl.await()
            // Add it to the list of Uris
            urls.add(downloadUri)
        }
    }
}

相关问题