wanna be dev 🧑‍💻

Cool 하고 Sick한 개발자가 되고 싶은 uzun입니다

A.K.A. Kick-snare, hyjhyj0901, h_uz99 solvedac-logo

Android/Issue Handling

💡 launchIn(Scope) vs Scope.launch 의 차이 | flow terminal operation

Kick_snare 2022. 8. 20. 20:56
728x90

개요

얼마전 안드로이드 개발 중 대략 난감한 상황에 처했다.

상황은 이러하다. 뷰모델에서 서버 api로 데이터를 받아오는 usecase를 실행시켜 값을 받아오는 간단한 함수를 작성 중 이였다.

코루틴 스코프에서 flow를 실행 시키기위해서

viewModelScope.launch{       flow.onEach { ... } } 

와 같은 코드를 작성하였다.

음 아무런 문제가 없어보인다. flow가 발행하는 하나하나 소비할 것이라고 생각했다.
하지만 이게 왠걸..

반환되는 데이터가 전부 null 값이지 않은가..

해결

그렇게 한참을 헤매다 해결책을 찾았다.

내가 쓴 코드의 단축어와 같은 Flow.launchIn(Scope) 를 사용하니 정상적으로 돌아가는 것이 아닌가...

WHY?

이유는 간단했다.
소비한다고 생각했던 onEach는 flow의 중간 연산자, 즉 맵퍼와 같은 역할을 가진 연산자였고 나는 terminal operation (collect, single, reduce) 등등을 사용하지 않은 것이다.

종료 연산자가 없으니 flow 자체가 시작되지 않은 것이였다.

나와 같은 멍청이가 이 글을 보고 도움이 되었으면 한다.

참고

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html

 

launchIn

Terminal flow operator that launches the collection of the given flow in the scope. It is a shorthand for scope.launch { flow.collect() }. This operator is usually used with onEach, onCompletion and catch operators to process all emitted values handle an e

kotlinlang.org

https://handstandsam.com/2021/02/19/the-best-way-to-collect-a-flow-in-kotlin-launchin/

 

The Best Way to Collect a Flow in Kotlin – launchIn – Handstand Sam

At some point you’ll need to collect (receive items) from a Flow (reactive stream) within a Kotlin Coroutine.  More than likely you will use a launch on a CoroutineScope, and then collect like this: scope.launch { flow .onEach { println(it) } .collect(

handstandsam.com

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/

 

Flow

Flow common An asynchronous data stream that sequentially emits values and completes normally or with an exception. Intermediate operators on the flow such as map, filter, take, zip, etc are functions that are applied to the upstream flow or flows and retu

kotlinlang.org

 

728x90