시배's Android

Kotlin Coroutines Deep Dive | 2장. 시퀀스 빌더 본문

Book/Kotlin Coroutines Deep Dive

Kotlin Coroutines Deep Dive | 2장. 시퀀스 빌더

si8ae 2024. 1. 15. 21:42
  • 코틀린의 시퀀스는 List나 Set과 같은 컬렉션이랑 비슷한 개념이지만, 필요할 때마다 값을 하나씩 계산하는 지연 처리를 합니다.
  • 요구되는 연산을 최소한으로 수행합니다.
  • 무한정이 될 수 있습니다.
  • 메모리 사용이 효율적입니다.
val seq = sequence {
	yield(1)
    yield(2)
    yield(3)
}

fun main() {
	for (num in seq) {
    	print(num)
    }
}
  • 인자는 수신 객체 지정 람다 함수입니다 (suspend SequenceScope<T>() -> Unit)
  • 람다 내부에서 수신 객체인 this는 SequenceScope<T>를 가리킵니다.
  • 중단을 지원하는 스레드로 처리하려면 유지하고 관리하는데 막대한 비용이 듭니다.
val fibonacci : Sequence<BigInteger> = sequence {
	val first = 0.toBigInteger()
    val second = 1.toBigInteger()
    while(true){
    	yield(first)
        val temp = first
        first += second 
        second = temp
    }
}

fun main() { 
	print(fibonacci.take(10).toList())
}