android/Kotlin: 请问如何实现 JavaScript 中的 promise 异步链式流程?

2020-12-04 15:56:54 +08:00
 sprinter

我有一个下载 object 类 DownloadManager, 作用是下载文件, 见如下代码所示.

我先调用这个类的 beginDownload 方法, 开始下载文件, 文件下载完成后该类会通过广播 BroadcastReceiver 发送下载成功的消息.

object DownloadManager {

var downloadID: Long = 0

fun beginDownload(context: Context, url: String): Long {

    val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), File(url).name)

    val request =

        DownloadManager.Request(Uri.parse(url))

            .setDestinationUri(Uri.fromFile(file)) // Uri of the destination file

            .setAllowedOverMetered(true) //  Allow download on Mobile network

    val dm = context.getSystemService(DOWNLOAD_SERVICE) as DownloadManager

    downloadID = dm.enqueue(request) // enqueue the download request.

    return downloadID

}



val br: BroadcastReceiver = object : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {

        val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)

        if (downloadID.toLong() === id) {

//下载成功 Toast.makeText(context, "Download complete", Toast.LENGTH_SHORT).show()

        }  }  }}

我的问题:

我以前用 JavaScript 时习惯用 promise 来根据下载成功与否执行下面动作, 代码如下:

new Promise(function(resolve, reject) {

用 DownloadManager 类 下载第一个文件

}).then(function(result) {

用 DownloadManager 类 下载第一个文件

}).then(function(result) {

用 DownloadManager 类 下载第一个文件

})

请问上述链式的 promise 结构在 android kotlin 里如何写?

谢谢指教! 小女感激不尽

1305 次点击
所在节点    程序员
6 条回复
karnaugh
2020-12-04 16:04:50 +08:00
RxAndroid ?
xFrye
2020-12-04 16:33:28 +08:00
可以看下 kotlin 的 flow
luwies
2020-12-04 16:45:53 +08:00
RxJava 应该是可以做到
kazeik
2020-12-04 18:16:31 +08:00
rxjava 可以
winterbells
2020-12-04 18:21:58 +08:00
用协程吧,可以把所有 then 行删掉,同步的写法
mxalbert1996
2020-12-05 10:56:49 +08:00
喜欢 Promise 的语法就用 RxJava,喜欢 async/await 的语法就用 coroutines

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/732155

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX