Android使用suspendCancellableCoroutine将回调转换为协程

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/122058124
本文出自【赵彦军的博客】

suspendCancellableCoroutine

普通的回调函数:

interface Result<T> {
    fun onSuccess(t: T)
    fun onFailed(e: Exception)
}

回调方法,模拟耗时操作

  fun longTimeMethod(result: Result<String>) {
        thread {
            Thread.sleep(5000)
            if (System.currentTimeMillis() % 10 > 6) {
                result.onSuccess("${System.currentTimeMillis()}")
            } else {
                result.onFailed(Exception("FAILED"))
            }
        }
    }

去掉回调,转换为挂起函数:

 suspend fun getResult(): String =
        suspendCancellableCoroutine {
            longTimeMethod(object : Result<String> {
                override fun onSuccess(t: String) {
                    if (it.isCancelled) return
                    it.resume(t)
                }

                override fun onFailed(e: Exception) {
                    it.resumeWithException(e)
                }

            })
        }

使用:

     GlobalScope.launch {
            try {
                val result = getResult()
            } catch (exception: Exception) {

            }
        }

源码分析:

我们看一下 it.resume()it.resumeWithException()方法,其实是调用 resumeWith(result: Result)
在这里插入图片描述

suspendCancellableCoroutine 和 suspendCoroutine 区别

  • 使用 suspendCancellableCoroutine 和 suspendCoroutine 都可以将回调函数转换为协程
  • SuspendCancellableCoroutine 返回一个 CancellableContinuation, 它可以用 resume、resumeWithException 来处理回调 和抛出 CancellationException 异常。它与 suspendCoroutine的唯一区别就是 SuspendCancellableCoroutine 可以通过 cancel() 方法手动取消协程的执行,而 suspendCoroutine 没有该方法。
  • 尽可能使用 suspendCancellableCoroutine 而不是 suspendCoroutine ,因为协程的取消是可控的

举个例子:使用网络请求数据时,如果请求时间过长,用户可以手动取消掉协程的执行。这时会抛出一个 CancellationException 异常,但是将该异常try{}catch{}捕获后就不会影响后续代码的执行。而使用 suspendCoroutine 只能干等着被 resume 或者 resumeWithException ,因为它没有该功能。

可以使用以下代码将PDF文件转换为图片: ```java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.pdf.PdfRenderer; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); File pdfFile = new File("path/to/pdf/file.pdf"); try { // create a new PdfRenderer object PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)); // get the number of pages in the PDF file final int pageCount = renderer.getPageCount(); // get the first page of the PDF file PdfRenderer.Page page = renderer.openPage(0); // create a new bitmap object Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888); // create a new canvas object Canvas canvas = new Canvas(bitmap); // set the background color of the canvas object canvas.drawColor(Color.WHITE); // render the PDF page into the canvas object page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); // set the bitmap image to the ImageView imageView.setImageBitmap(bitmap); // close the page object page.close(); // close the renderer object renderer.close(); // save the bitmap image as a JPEG file FileOutputStream out = new FileOutputStream("path/to/output/file.jpg"); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意替换代码中的文件路径。此代码将PDF文件的第一页转换为图片,并将其显示在ImageView中,然后将其保存为JPEG文件。你可以更改代码以转换多页PDF文件或更改输出图像的格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值