Flow 연산자 : map VS mapLatest

hyihyi·2024년 8월 3일

mapLatest는 비동기, map은 동기가 아니었네??

처음엔 mapLatest 실행하다가 delay 나오니까 다시 flow로 가길래 비동기 방식으로 동작한다고 생각했는데 그게 아니라 그냥 작업 중단하고 처음부터 시작하는 거였다.

map

map에 들어온 순간 중간에 새로운 값이 들어와도 map은 현재 작업을 중단하지 않고 끝까지 완료된다.

val flow = flow {
    emit(1)
    emit(2)
}.map {
    println("Processing $it")
    delay(200)
    println("Processed $it")
}.collect {
    println("Collected $it")
}
Processing 1 //emit(1) 직후에 바로 출력
Processed 1
Collected 1 // map에 들어온 순간 끝까지 실행
Processing 2
Processed 2
Collected 2

emit(1) 직후에 map 안의 출력문이 실행된다.

mapLatest

작업이 진행 중일 때 새로운 값이 들어오면, 현재 작업은 중단되고, 새로운 값에 대한 작업이 처음부터 다시 실행된다.

val flow = flow {
    emit(1)
    delay(100)
    emit(2)
}.mapLatest {
    println("Processing $it")
    delay(200)
    println("Processed $it")
}.collect {
    println("Collected $it")
}
Processing 1
Processing 2
Processed 2
Collected 2

"Processing 1"을 출력하고 나서 delay(200)을 실행하는 도중에 emit(2)가 실행되어서 새로운 값이 들어왔기 때문에 하던 작업을 멈추고 mapLatest의 처음부터 실행한다.

profile
내가 이해하기 쉽게 쓰는 블로그

0개의 댓글