[코루틴]작업 캔슬하지 못하게 하기

2025. 4. 30. 13:36Kotlin

728x90

안녕하세요~ 

코루틴을 배우면서, 어떤 로직에는 작업이 캔슬되지 않아야 하는 경우가 있습니다. 

상상을 해보자면, 안드로이드 앱을 사용하면서 자동 동기화 기능이 그것이죠. 

사용자가 다른 작업을 하더라도 보이지 않은 영역에서는 그 작업을 계속 이어가야 하죠.

 

예제 코드입니다.

import kotlinx.coroutines.*

class NoneCancellationBlock {


}

suspend fun doCountOneTwoThreeNoneCancel() = coroutineScope {
    val job1=  launch {
    	// withContext 와 NonCancellable은 코틀린에서 제공되는 것입니다.
        withContext(NonCancellable){
            println("launch : ${Thread.currentThread().name}")
            delay(1000L)
            println("3!")
            // 상상해보면, 안드로이드 Room DB와 사용자의 입력을 자동으로 저장합니다. 
        }
        delay(1000L)
        
        println("Job1 End")
    }

    val job2=  launch {
        withContext(NonCancellable){
            println("launch : ${Thread.currentThread().name}")
            delay(1000L)
            println("1!")
        }
        delay(1000L)
        println("Job2 End")
        // job1이 끝나면, Room DB와 서버와 통신하여 동기화합니다. 
    }

    val job3=  launch {
        withContext(NonCancellable){
            println("launch job 1: ${Thread.currentThread().name}")
            delay(1000L)
            println("2!")
        }
        delay(1000L)
        println("Job3 End")
    }

    delay(800L)
    job1.cancel()
    job2.cancel()
    job3.cancel()
}

fun main() = runBlocking {
    doCountOneTwoThreeNoneCancel()
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

 

출력 예시입니다. 

 

 

[환경]

IDE :  Android Studio Flamingo | Android Studio 2024.3.1 Patch (Help메뉴 > About 항목 클릭)

언어 : Kotlin 2.0.21 ( 안드로이드 프로젝트 경로 > gradle > lib.versions.toml 


[reference]

(현재 강의는 내려감 )

효과적인 비동기처리를 위한 Kotlin Coroutines & Flow 마스터 by 김용욱  https://fastcampus.co.kr/story_article_dev_red_kyu 

ViewModel과 함께 LiveData 사용하기  :  https://developer.android.com/codelabs/basic-android-kotlin-training-livedata?hl=ko#0

android-basics-kotlin-unscramble-app 의 GitHub 링크 : https://github.com/google-developer-training/android-basics-kotlin-unscramble-app/tree/starter

 

[도움]

 

1. 응원 댓글은 글 쓰는데 힘이 됩니다.

2. 공감도 글 쓰는데 힘이 됩니다. 

3. 광고 한번 클릭해 주시면 힘은 두 배가 됩니다. 

4. 혹시라도 부족한 부분이 있다면 덧글로 남겨주세요. 남기시면, 더 나은 글을 쓸 재료가 됩니다.

 

 

728x90