android/Kotlin: 请问如何实现 JavaScript 中的 promise 异步链式流程?
資深大佬 : sprinter 4
我有一个下载 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)