• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    미해결

Coroutine, Flow 질문

24.01.28 16:58 작성 조회수 91

0

안녕하세요. 강의 잘 듣고 있습니다!
아래 질문이랑 거의 비슷한 질문이긴한데 확실히 하고싶어 문의드립니다

 

 

import kotlinx.coroutines.*

import kotlinx.coroutines.flow.*

fun main() = runBlocking<Unit> {

// Launch a concurrent coroutine to check if the main thread is blocked

launch {

for (k in 1..3) {

println("I'm not blocked $k")

delay(100)

}

}

// Collect the flow

simple().collect { value -> println(value) }

// println("test")

}

fun simple(): Flow<Int> = flow { // flow builder

for (i in 1..3) {

delay(100) // pretend we are doing something useful here

emit(i) // emit next value

}

}

 

  1. runBlocking{} 내부에서 launch {} 로 코루틴이 생성

  2. 그다음 simple().collect{} 코드가 실행되는데 이것도 코루틴으로서 생성

  3. launch 로 생성한 코루틴이 실행 -> println("I'm not blocked $k") 코드 출력

  4. flow 코루틴 실행-> collect 된 value 출력

  5. 3,4 반복

이해한게 맞을까요?

 

그리고 타이밍에 따라서 결과값이

1
I'm not blocked 1

2

I'm not blocked 2

3

I'm not blocked 3

 

이렇게 나올수도 있나요? 챗지피티는 타이밍 때문에 출력 순서가 바뀔수 있다고 해서요 ..

답변 1

답변을 작성해보세요.