본문 바로가기

코틀린

코루틴 실수할 수 있는 부분 모음

반응형

안드로이드에는 라이프싸이클 스코프(lifecycle scope)라는게 존재합니다.

해당 스코프를 이용해 릭이 나지않게 사용하는데요.

Activity와 Fragment의 경우 lifecycleScope, viewLifecycleScope가 존재하죠. ViewModel의 경우 ViewModelScope가 있습니다.

check 해야 할 포인트 1.

Scope의 child Scope에서 취소가 될 경우 parent 까지 취소가 전파됩니다. 따라서 parent가 같은 child는 모두 취소가 됩니다.

val testScope = CoroutineScope(Dispatchers.Main)
    
    fun testJob1() {
        testScope.launch { 
            // 여기서 CancellationException이 발생된다면
        }
    }
    
    fun testJob2() {
        testScope.launch { 
            // parentScope를 같이 쓰고 있는 여기까지 cancel이 전파됩니다.
        }
    }

 

포인트 2.

"전파 안시키려면 Scope에 Job 혹은 SuperVisiorJob을 더해서 쓰면된다더라!
그렇게 쓰면 문제 해결될 듯!!"

에서 나오는 문제 점 단순히 supervisorJob을 더하기만 한다면 새로운 콘텍스트로 인식해서 parentScope의 cancel을 전파받지 못합니다.

val testScope = CoroutineScope(Dispatchers.Main)

    fun testJob1() {
        testScope.launch(Job()) {
            // 여기서 CancellationException이 발생한다고 testJob2까지 전파되진 않지만
            // testScope 자체가 cancel될때 같이 캔슬되진 않음
        }
    }

    fun testJob2() {
        testScope.launch {
            // testScope 자체가 cancel될 때 같이 캔슬됨
        }
    }

해결 방법

val testScope = CoroutineScope(Dispatchers.Main)

    fun testJob1() {
        CoroutineScope(SupervisorJob(testScope.coroutineContext[Job])).launch() {
            // 이렇게하면 의도대로 cancel이 parent에 전파되지 않고 parentScope의 취소에 반응함
        }
    }

    fun testJob2() {
        testScope.launch {
            // testScope 자체가 cancel될 때 같이 캔슬됨
        }
    }
반응형