Async task could not keep up with for loop (firebase)

大憨熊 提交于 2021-01-28 12:13:14

问题


  for (Uri mUri : mSelected) 
   {
       imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
       imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
       db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
   }

So, now i am working with firestore and firebase storage. I uploaded (multiple) images to the storage, and when it is uploaded, i get the download url and wants to add it into my firestore. So, the problem is, only the last image is added into firestore, all images are added into storage, but only the last imgUrl is added into firestore. Since firebase uses async tasks i suspect it is because the update task could not keep up with the loop. Any help is very much appreciated !!!


回答1:


I think the problem might be with imagesRef, it is declared outside of for (Uri mUri : mSelected) {...} and therefore it is being replaced before addOnSuccessListener(...) responds.

So, declare it locally to for (Uri mUri : mSelected) {...} and see if it will not resolve the issue. Like this

for (Uri mUri : mSelected) 
{
       var imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
       imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
       db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
 }


来源:https://stackoverflow.com/questions/58911409/async-task-could-not-keep-up-with-for-loop-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!