Coroutines And Firebase: How to Implement Javascript-like Promise.all()

非 Y 不嫁゛ 提交于 2021-01-29 17:36:57

问题


In Javascript, you can start two (or more) asynchronous tasks simultaneously, wait both of them to finish and then do something/continue:

const [firstReturn, secondReturn] = await Promise.all([
    firstPromise,
    secondPromise ];

// Do something with first and second return.

What I want to do in Kotlin (Android) is to start downloading two images from Firebase and when both downloads are completed - update the UI with them. So I have two Firebase async functions like this:

FirebaseStorage.getInstance().reference..child("Images/Events/$eventID/eventPhoto.jpeg").getBytes(1024 * 1024).addOnSuccessListener { byteArray ->
                event.image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
            }
//And another one with different path

I thought about using Kotlin's "async/await" but since I can't return a value from Firebase function, it didn't work. Is there a straightforward way to do this in Kotlin so I can start to download both images at the same time and do some work after both of them are downloaded?


回答1:


You will likely want to make use of Play services integration with coroutines that's documented here. What you get from this library is an extension function for Task (returned by Play and Firebase async APIs) called await() that you can use in a coroutine to defer execution until it's done.



来源:https://stackoverflow.com/questions/57119804/coroutines-and-firebase-how-to-implement-javascript-like-promise-all

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