• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

코루틴 스코프

24.02.15 14:32 작성 조회수 135

0

코드를 보다보면 코루틴 스코프를 쓸 때, 소문자로 coroutineScope { } 블락이 있는 경우가 있고 대문자로 시작하는 CoroutineScope(Dispatchers.Main).launch { } 이런식으로 된 코루틴스코프가 있는데, 각각 어떤 차이이며 어느 상황에 각각을 써야하나요?

답변 1

답변을 작성해보세요.

0

안녕하세요! lkckss123님! 😊 앞선 질문 - https://www.inflearn.com/questions/1179607/coroutinescope-%EC%99%80-withcontext-%EC%9D%98-%EC%B0%A8%EC%9D%B4%EB%A5%BC-%EC%9E%98-%EB%AA%A8%EB%A5%B4%EA%B2%A0%EC%8A%B5%EB%8B%88%EB%8B%A4 - 에서 이어지는 것으로 생각됩니다!

 

CoroutineScope(Dispatchers.Main).launch { } 는 suspend 함수가 아니고, 새로운 코루틴 영역을 시작하기 위해 사용하는 것으로 알고 계실겁니다.

 

coroutineScope()CoroutineScope()과 다르게 suspend 함수이고, 오히려 withContext()에 가깝습니다. coroutineScope() 안에 추가적인 코루틴을 만들면, 해당 코루틴들을 하나로 묶어 줄 수 있게 되죠. 다만 withContext()가 CoroutineContext를 바꾸면서 새로운 코루틴을 만들었다면, coroutineScope()은 딱히 context는 바꾸지 않습니다.

 

coroutineScope()은 다음 예제를 보시면 이해가 잘 되실거에요!

fun main(): Unit = runBlocking {
  printWithThread("START")
  printWithThread(calculateResult())
  printWithThread("END")
}

suspend fun calculateResult(): Int = coroutineScope {
  val num1 = async {
    delay(1_000L)
    10
  }

  val num2 = async {
    delay(1_000L)
    20
  }

  num1.await() + num2.await()
}

여기서 만약 calculateResultcoroutineScope 이 아닌 CoroutineScope 으로 만들려 한다면, Int 를 반환하지 못하고 Job 자체를 반환해야 할거에요!

fun main(): Unit = runBlocking {
    printWithThread("START")
    printWithThread(calculateResult())
    printWithThread("END")
}

fun calculateResult(): Job = CoroutineScope(Dispatchers.IO).async {
    val num1 = async {
        delay(1_000L)
        10
    }

    val num2 = async {
        delay(1_000L)
        20
    }

    num1.await() + num2.await() // 결과를 보고 싶다면 출력을 해야 한다!
}

또한 coroutineScope 을 사용했을 때는 두 개의 async가 동작하고 덧셈 결과인 30이 출력되기 전까지 END 가 출력되지 않지만, CoroutineScope()을 사용하게 되면 START -> Job 반환 -> END 출력으로 실제 async 두 개가 동작할 때까지 대기하지 않습니다.

 

따라서 coroutineScope() 같은 경우는 진작 코루틴영역이 존재하는 상황에서 앞으로 만들 몇몇 코루틴을 묶어 주고, 해당 코루틴들을 먼저 실행시키고 싶을 때 사용한다고 보시면 되겠습니다.

감사합니다! 🙏