依次启动相同协程的实例

时间:2019-07-27 03:49:27

标签: android asynchronous kotlin kotlin-coroutines

我有一个场景,其中有多个URL可以下载PDF。我需要为每个URL进行网络调用,处理pdf,将其发送到打印机,等待打印机完成处理,然后继续下一个URL。我试图绕过协程,但我不明白如何在这里应用它。

在这里,我要对数组中的每个URL进行调用并进行调用,在回调中,我调用方法“ printImage”,将pdf发送给打印机,然后我可以侦听它的完成方式,我在这里实现协程吗?在这种情况下,方法“ printImage”应为协程

fun printLabels(labels: HashMap<Long, String>) {
    for (item in labels.values) {
        val call = labelService.getPDF(item)
        call.enqueue(
            object : retrofit2.Callback<ResponseBody> {
                override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {

                    val outputDir = cacheDir
                    val outputFile = File.createTempFile("prefix", "extension", outputDir)
                    Files.asByteSink(outputFile).write(response.body()!!.bytes())

                    val bitmap = getBitmap(outputFile)!!

                    printImage(bitmap)
                }

                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                    Timber.e(t.localizedMessage)
                }

            }
        )
    }
}


  fun printImage(bm: Bitmap) {
    Thread(Runnable {
        printerRepository.currentPrinter.value?.let { printer ->
            if (printer.startCommunication()) {
                val result = printer.printImage(bm)
                if (result.errorCode != PrinterInfo.ErrorCode.ERROR_NONE) {
                    Timber.d("ERROR - " + result.errorCode)
                } else {

                }
                printer.endCommunication()
            } else {
                printerRepository.printerTestPassed.postValue(false)
            }
        }
    }).start()
}

0 个答案:

没有答案