Constructing a coroutine scope

참치돌고래·2022년 12월 12일
0

CoroutineScope는 한 개의 CoroutineContext를 가지고 있다.

interface CoroutineScope {
	val coroutineContext: CoroutineContext
}

그렇기 때문에 바로 coroutine builder를 호출하여 클래스를 생성할 수 있다.

class ExampleClass : CoroutineScop {
	override val coroutineContext : CoroutineContext = Job()
    
    fun onStart() {
    	launch{
        }
    }
}

하지만 이렇게 직접적으로 coroutine builder를 호출하여 클래스를 생성하는 것은 cancel, ensureActive와 같은 메소드들을 다른 coroutineScope에서 호출하여 쉽고 취소되어
다시는 시작이 안될 수도 있다.
그렇기 때문에, coroutineScope factory를 통해 현재 scope를 유지하면서 coroutine builder를 호출하여 사용하는 것이 안전하다.

	public fun CoroutineScope(
	context: CoroutineContext
    ) : CoroutineScope = 
    	ContextScop(
        	if (context[Job] != null) context
            else context + Job()
        )
     internal class ContextScope(
          context : CoroutineContext
     ) : CoroutineScope {
          override val coroutineContext : CoroutineContext = context
          override val toString() : ...
     }
   

이렇게 구현하여 사용을 하게 되면, CoroutineScope 범위 안에 Job이 들어가게 된다.

profile
안녕하세요

0개의 댓글