协程和Firebase:如何实现类似Java的Promise.all() [英] Coroutines And Firebase: How to Implement Javascript-like Promise.all()

查看:93
本文介绍了协程和Firebase:如何实现类似Java的Promise.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,您可以同时启动两个(或多个)异步任务,等待它们都完成,然后执行一些操作/继续:

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.

我想在Kotlin(Android)中做的是开始从Firebase下载两个图像,并且两个下载都完成后-用它们更新UI.所以我有两个这样的Firebase异步函数:

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

我曾考虑过使用Kotlin的异步/等待"功能,但由于无法从Firebase函数返回值,因此无法正常工作.在Kotlin中是否有一种简单的方法可以做到这一点,所以我可以同时开始下载两个图像,并在两个图像都下载后做一些工作?

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?

推荐答案

您可能想利用Play服务与协程的集成,该程序已记录在

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.

这篇关于协程和Firebase:如何实现类似Java的Promise.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆