0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AndroidStudio: Coroutine の使い方

Last updated at Posted at 2023-10-24

こちらのプログラムを AndroidStudio で実行して見ました。
Kotlin: Coroutine の使い方

環境設定

app/build.gradle.kts
(省略)
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
(省略)

プログラム

MainActivity.kt
package com.example.oct2402

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // main_proc を非同期で呼び出すために CoroutineScope を作成
        CoroutineScope(Dispatchers.Main).launch {
            main_proc()
        }
    }

    // main_proc を非同期関数に変更
    suspend fun main_proc() = coroutineScope {
        val aa = 10
        val bb = 20
        var cc = 0
        var dd = 0

        // バックグラウンドスレッドで計算を行う
        launch(IO) {
            delay(1000)
            println("Kotlin Coroutines World!")
            cc = aa + bb
            dd = aa - bb
            println("PP: cc = $cc\t\tdd = $dd")
        }

        // メインスレッドで "こんにちは" を表示
        println("こんにちは")

        println("QQ: cc = $cc\t\tdd = $dd")
    }
}

実行結果

image.png

15:41:20.237  I  こんにちは
15:41:20.238  I  QQ: cc = 0		dd = 0
15:41:21.242  I  Kotlin Coroutines World!
15:41:21.242  I  PP: cc = 30		dd = -10
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?