V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sprinter
V2EX  ›  程序员

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

  •  1
     
  •   sprinter · 2020-12-04 15:56:54 +08:00 · 1281 次点击
    这是一个创建于 1210 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有一个下载 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 里如何写?

    谢谢指教! 小女感激不尽

    6 条回复    2020-12-05 10:56:49 +08:00
    karnaugh
        1
    karnaugh  
       2020-12-04 16:04:50 +08:00
    RxAndroid ?
    xFrye
        2
    xFrye  
       2020-12-04 16:33:28 +08:00
    可以看下 kotlin 的 flow
    luwies
        3
    luwies  
       2020-12-04 16:45:53 +08:00
    RxJava 应该是可以做到
    kazeik
        4
    kazeik  
       2020-12-04 18:16:31 +08:00 via iPhone
    rxjava 可以
    winterbells
        5
    winterbells  
       2020-12-04 18:21:58 +08:00 via Android
    用协程吧,可以把所有 then 行删掉,同步的写法
    mxalbert1996
        6
    mxalbert1996  
       2020-12-05 10:56:49 +08:00 via Android
    喜欢 Promise 的语法就用 RxJava,喜欢 async/await 的语法就用 coroutines
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1063 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 19:05 · PVG 03:05 · LAX 12:05 · JFK 15:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.