简体   繁体   English

Kotlin 协程在 Android 中的使用

[英]Kotlin Coroutines usage in Android

I'm trying to use Kotlin Coroutines for better performance.我正在尝试使用 Kotlin 协程来提高性能。

But I'm not sure is it the correct way to use it, so I'd like to have experts review.但我不确定它是否正确使用它,所以我想请专家审查。

After taking a photo with camera, the screen is the blackout for half second while the image processing I guess.用相机拍照后,我猜在图像处理时屏幕是半秒的黑屏。

The original code was,原来的代码是,

fun uploadPhoto(data: Intent): Observable<Response> {
    val bitmap = data.extras.get("data") as Bitmap
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)

    val baseDir = Environment.getExternalStorageDirectory()
    val file = File(baseDir, Calendar.getInstance().timeInMillis.toString() + ".jpg")
    val fileOutputStream = FileOutputStream(file)
    fileOutputStream.write(bytes.toByteArray())
    fileOutputStream.close()


    return uploadMedia(file)
}

and after I read this tutorial,https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html在我阅读本教程后,https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html

I changed it to,我改成,

fun uploadPhoto(data: Intent): Observable<Response> {
    val baseDir = Environment.getExternalStorageDirectory()
    val file = File(baseDir, Calendar.getInstance().timeInMillis.toString() + ".jpg")

    launch {
        val bitmap = data.extras.get("data") as Bitmap
        val bytes = compressBitMap(bitmap).await()
        val fileOutputStream = FileOutputStream(file)
        fileOutputStream.write(bytes.toByteArray())
        fileOutputStream.close()
    }

    return uploadMedia(file)
}

private fun compressBitMap(bitmap: Bitmap) = async(CommonPool) {
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    return@async bytes
}

But I don't see any difference.但我看不出有什么区别。

What I want to do thing is, I want to run Compressing Bitmap and fileOutputStream jobs in Background to prevent bothering MainThread.我想做的是,我想在后台运行 Compressing Bitmap 和 fileOutputStream 作业以防止打扰 MainThread。

Does it make the better performance?它是否具有更好的性能?

Coroutines are executed in "CoroutineContexts", you appear to be using an older version of the libs, in newer versions you should always specify the context by using launch(UI) or launch(CommonPool).协程在“CoroutineContexts”中执行,您似乎使用的是旧版本的库,在新版本中,您应该始终使用launch(UI) 或launch(CommonPool) 指定上下文。 I don't know by default which context is your "launch" using, but I guess is UI.默认情况下,我不知道您的“启动”使用的是哪个上下文,但我猜是 UI。 If that's correct, you are in deed waiting in the UI thread for the compressBitMap completion, blocking the UI thread (A pointless coroutine use)如果这是正确的,您实际上是在 UI 线程中等待 compressBitMap 完成,从而阻塞了 UI 线程(无意义的协程使用)

Try to use launch(CommonPool) instead and see if the magic happens.尝试使用 launch(CommonPool) 代替,看看魔法是否发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM