问题
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