Coroutine-Kotlin(Definition & Use)

JaeYeon Won·2024년 8월 27일

Kotlin

목록 보기
1/1

What is Coroutine?[1]

A coroutine is an instance of a suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.

coroutine은 suspendable(지연 가능한) computation들의 객체이다. thread와 비슷하지만 분명 thread와는 다르다.

Coroutine의 구성은 어떻게 되는가? 즉 어떤 형태로 코드를 짜야 작동이 되는가?

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed
}

이는 kotlin 공식문서에서 보여주는 하나의 코드다. 해당 코드를 살펴보면 다음과 같다.

coroutine builder(ex) runBlocking)

runBlocking is also a coroutine builder that bridges the non-coroutine world of a regular fun main() and the code with coroutines inside of runBlocking { ... } curly braces. This is highlighted in an IDE by this: CoroutineScope hint right after the runBlocking opening curly brace.

runBlocking의 경우 CoroutineScope과 동일한 역할을 해준다(?)
Q -> 왜 coroutine builder인데 CoroutineScope처럼 쓸 수 있는가?

coroutine builder(ex) launch)

launch is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work independently. That's why Hello has been printed first.

launch는 새로운 coroutine을 기존 코드와 함께 독립적으로 동시에 실행 가능한 형태로 만들어준다.

-> launch/async의 경우 오로지 coroutineScope 안에서만 선언 가능하다.

suspending function(ex) delay, suspend fun)

delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.

왜 CoroutineScope와

Coroutine 라이브러리가 github에 이미 오픈소스로 있고 다음과 같이 설명한다.

'launch' and 'async' coroutine builders returning 'Job' and 'Deferred light-weight futures' with cancellation support;

참고용으로 자료형에 대한 설명

  1. CoroutineScope이라는 인터페이스가 먼저 있다. 형태는 다음과 같다.
코드를 입력하세요

suspend function 내에서 coroutine을 정의하는 경우

-> 반드시 function이 반환되면 coroutine도 종료되어야 한다.

Coroutine과 관련된 사실(+근거)

  • Coroutine은 thread와 비슷하지만 thread는 아니다.[1]

  • kotlin은 kotlinx.coroutine과 같은 라이브러리 형태로 사용 가능하다. kotlin의 standard library에 포함되어 있지 않다.

Android로 보는 Coroutine의 용례

이건 다음 글에서

글 읽어보시고 QnA 및 수정 비판 사항 얼마든지 환영입니다!

댓글로 많이 남겨주세요~

참조자료

  1. Coroutines basics - Kotlin

  2. Java applets and applications - IBM

profile
Hello, My name is JaeYeon Won and I'm studying software development.

0개의 댓글