Kotlin协程快速入手

将项目改为支持Kotlin

(如果项目本身就是kotlin项目,这一步可以忽略)

  1. 在项目的build.gradle的dependencies下面加上
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0" (版本可以改变,后面肯定会更新.)
  2. 在module里的build.gradle加上
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'

引入库

在module的build.gradle的dependencies加上
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'

两个简单使用例子

GlobalScope.launch(context = Dispatchers.IO) {
            //延时一秒
            delay(1000)
            Log.e("MainActivity","launch");
        }
        //主动休眠两秒,防止 JVM 过快退出
        Log.e("MainActivity","start");
        Thread.sleep(2000)
        Log.e("MainActivity","end");

//        val time = measureTimeMillis {
        GlobalScope.launch  {
                val asyncA = async {
                    delay(3000)
                    1
                }
                val asyncB = async {
                    delay(4000)
                    2
                }
                Log.e(MainActivity.javaClass.name,"msg:"+asyncA.await() + asyncB.await())
            }

运行结果:
2022-06-07 17:46:59.152 8021-8021/com.laotie.test E/MainActivity: start
2022-06-07 17:47:00.161 8021-8065/com.laotie.test E/MainActivity: launch
2022-06-07 17:47:01.152 8021-8021/com.laotie.test E/MainActivity: end
2022-06-07 17:47:01.154 8021-8021/com.laotie.test E/com.laotie.test.MainActivityCompanion: msg:12

详细知识可以看看这个博客:

https://juejin.cn/post/6908271959381901325

你可能感兴趣的:(Kotlin协程快速入手)