개발 공부/kotlin

Coroutines/코루틴 기초 1

yong_DD 2021. 9. 14. 22:43
코루틴이란?

코루틴은 비동기적으로 실행되는 코드를 간소화하기 위해 (Android에서) 사용할 수 있는 동시 실행 설계 패턴.

 

사실 나 같은 초보 개발자에게는 설명을 읽어도 무슨 말인지 잘 모르겠다.

 

그래서 기초지만 내가 이해한 대로 다시 정리!

→ 보통 코드를 작성하면 순서대로 동작을 하게 되는데 코루틴으로 작성을 하게 되면 루틴의 순서대로 동작하게 되는 것!

→ 모든 루틴이 끝날 때까지 기다려주는 것(끝난 후에  return)

→ routine에 delay가 있을 경우(thread sleep 같은 역할) 딜레이 만큼 다른 루틴을 실행 후 (중단) 다시 재개


1. launch / runBlocking / delay

- launch와 runBlocking은 새로운 coroutine을 생성

(- runBlocking은 자식 스레드가 완료될 때까지 현재 스레드를 block)

- delay는 thread sleep 같은 것 ( thread 보단 효율성이 높음!)

fun main() = runBlocking { // this: CoroutineScope
    launch { 
        delay(1000L) 
        println("World!") 
    }
    println("Hello") 
}

1. runBlocking로 생성된  coroutine1은 delay가 없기 때문에 바로 Hello를 출력 후 대기

2. launch로 생성된 coroutine2는 delay 1000L(1초)가 지난 후 World!를 출력 → 완료

[결과]
Hello 
World!

 

2. join

- coroutine이 끝날 때까지 대기

fun main(){
	val job = launch {
  	  delay(1000L)
   	 println("World!")
	}
	println("Hello")
	job.join() 
	println("Done") 
}

1. launch로 생성된 coroutine1이 delay 1000L을 1000L를 대기(중단 후 다음 코드)

2. Hello를 출력

3. coroutine1이 delay 1000L을 기다려  World!를 출력

3. 그 다음 코드인 Done 을 출력

[결과]
Hello 
World!
Done

 

3. suspend

- 다른 function을 coroutine을 사용할 때 !

- suspend를 붙이지 않으면 안된다.

fun main() = runBlocking { // this: CoroutineScope
    launch { doWorld() }
    println("Hello")
}

suspend fun doWorld() {
    delay(1000L)
    println("World!")
}

1. lauch로 생성된 coroutine1이 1000L를 대기(중단 후 다음 코드)

2. Hello를 출력

3.  1000L 지난 후 coroutine1이 World!를 출력 후 완료

[결과]
Hello 
World!

 

자세한 사항 ↓

https://kotlinlang.org/docs/coroutines-basics.html#scope-builder-and-concurrency

 

후기)

Rx 보다 진입이 쉽다 그래서 시작했는데,

flutter를 잠깐 공부했을 때 좋았던 기능들을 떠올리게 해서 좋았고 간만에 새로운 것을 공부하다 보니 흥미진진!

빨리 배워서 실전에 써보고 싶다!