shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기
공유 연산자로 콜드 Flow를 핫 스트림으로 변환해 보세요.
shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기은(는) CoddyKit의 무료 Kotlin Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Kotlin Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
콜드 플로와 핫 플로 비교
콜드 플로는 수집기마다 다시 시작되고, 핫 플로는 하나의 업스트림 구독을 공유합니다. 여러 수집기가 구독할 때 콜드 플로를 핫 플로로 변환하면 중복 작업을 피할 수 있습니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun expensiveFlow() = flow {
println("Starting upstream work") // runs once if shared
repeat(3) { delay(100); emit(it) }
}
fun main() = runBlocking {
val cold = expensiveFlow()
// Two collectors = two executions:
launch { cold.collect { } }
launch { cold.collect { } }
delay(500)
coroutineContext.cancelChildren()
}shareIn 기초
flow.shareIn(scope, started, replay)은 콜드 Flow를 SharedFlow로 변환하고 하나의 업스트림 구독을 공유합니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val cold = flow {
println("Upstream started once")
repeat(5) { delay(100); emit(it) }
}
val hot = cold.shareIn(this, SharingStarted.Eagerly, replay = 0)
launch { hot.collect { println("A: $it") } }
launch { hot.collect { println("B: $it") } }
delay(600)
coroutineContext.cancelChildren()
}stateIn 기초
flow.stateIn(scope, started, initialValue)은 StateFlow로 변환합니다. StateFlow는 항상 값을 가지며 1개의 값을 재생합니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val cold = flow { delay(100); emit(42) }
val state: StateFlow<Int> = cold.stateIn(
scope = this,
started = SharingStarted.Eagerly,
initialValue = 0
)
println(state.value) // 0 immediately
delay(200)
println(state.value) // 42 after upstream emits
coroutineContext.cancelChildren()
}SharingStarted.Eagerly
Eagerly: 구독자 수와 관계없이 shareIn/stateIn을 호출하는 즉시 업스트림이 시작됩니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val flow = flow {
println("Eagerly started")
emit(1)
}.shareIn(this, SharingStarted.Eagerly)
// Upstream already running even before any collect
delay(50)
launch { flow.collect { println(it) } }
delay(100)
coroutineContext.cancelChildren()
}SharingStarted.Lazily
Lazily: 첫 번째 구독자가 구독할 때 업스트림이 시작되고, 구독자가 0명이 되어도 중지되지 않습니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val flow = flow {
println("Lazily started on first subscriber")
repeat(3) { delay(100); emit(it) }
}.shareIn(this, SharingStarted.Lazily, replay = 1)
delay(50) // no subscriber yet — not started
launch { flow.collect { println(it) } } // triggers start
delay(400)
coroutineContext.cancelChildren()
}SharingStarted.WhileSubscribed
WhileSubscribed(stopTimeout): 첫 번째 구독자가 참여하면 업스트림이 시작되고, 마지막 구독자가 떠난 후 stopTimeout밀리초가 지나면 중지됩니다. ViewModels에 적합합니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val flow = flow {
println("Started")
repeat(10) { delay(100); emit(it) }
}.shareIn(this, SharingStarted.WhileSubscribed(500))
val job = launch { flow.collect { print("$it ") } }
delay(300)
job.cancel() // subscriber left
delay(200) // within 500ms stop timeout — still running
launch { flow.collect { print("resume $it ") } }
delay(500)
coroutineContext.cancelChildren()
}일반적인 ViewModel 패턴
Android ViewModels에서는 stateIn(viewModelScope, WhileSubscribed(5000), initialValue)를 사용해 저장소 플로를 변환하면 플로를 공유하고 구성 변경에도 유지할 수 있습니다.
import kotlinx.coroutines.flow.*
// In ViewModel:
// val uiState: StateFlow<UiState> = repository
// .dataFlow()
// .map { UiState.Success(it) }
// .stateIn(
// scope = viewModelScope,
// started = SharingStarted.WhileSubscribed(5_000),
// initialValue = UiState.Loading
// )
fun main() { println("WhileSubscribed(5000) is the recommended ViewModel pattern") }shareIn과 stateIn 비교
shareIn → SharedFlow(현재 값이 없고 재생 개수를 설정할 수 있음). stateIn → StateFlow(항상 값을 가지며 replay=1). 소비자에게 현재 상태가 필요한지에 따라 선택합니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val cold = (1..3).asFlow().map { it * 10 }
// SharedFlow — no initial value:
val shared: SharedFlow<Int> = cold.shareIn(this, SharingStarted.Eagerly, replay = 1)
// StateFlow — always has a value:
val state: StateFlow<Int> = cold.stateIn(this, SharingStarted.Eagerly, 0)
delay(100)
println("shared cache: ${shared.replayCache}")
println("state value: ${state.value}")
coroutineContext.cancelChildren()
}재생 캐시의 상충 관계
재생 개수가 많을수록 늦게 구독한 구독자가 더 많은 기록을 볼 수 있지만 메모리도 더 많이 사용합니다. UI 상태에는 replay=1(stateIn)이면 충분합니다. 이벤트 로그에는 더 많은 재생이 필요할 수 있습니다.
import kotlinx.coroutines.flow.*
// replay=0: no history, only future events
// replay=1: last value (equivalent to stateIn)
// replay=N: last N events — use for message feeds, logs
// Trade-off: memory vs subscriber freshness
fun main() { println("Choose replay based on late-subscriber requirements") }공유되지 않은 플로의 위험
공유하지 않으면 각 Compose 수집기나 ViewModel 관찰자가 업스트림을 다시 실행하므로 네트워크 호출과 데이터베이스 쿼리가 중복됩니다. 비용이 큰 플로는 항상 공유하십시오.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun expensiveApi() = flow {
println("API CALL") // without sharing: once per collector
emit("data")
}
fun main() = runBlocking {
val shared = expensiveApi().shareIn(this, SharingStarted.Lazily, replay = 1)
launch { shared.collect { } } // one API call, shared
launch { shared.collect { } } // same emission
delay(200)
coroutineContext.cancelChildren()
}공유 시 리소스 정리
공유 플로의 스코프가 취소되면 업스트림 플로도 취소되고 finally 블록이 실행되므로 리소스가 올바르게 정리됩니다.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun resourceFlow() = flow {
try { repeat(10) { delay(100); emit(it) } }
finally { println("Upstream cleaned up") }
}
fun main() = runBlocking {
val scope = CoroutineScope(SupervisorJob())
val shared = resourceFlow().shareIn(scope, SharingStarted.Eagerly)
launch { shared.collect { print("$it ") } }
delay(250)
scope.cancel() // upstream cleanup runs
delay(100)
}빠른 확인
Android ViewModels에 권장되는 SharingStarted 전략은 무엇인가요?
요약
shareIn은 SharedFlow로 변환하고, stateIn은 StateFlow로 변환합니다. ViewModels에서는 리소스를 절약하기 위해 WhileSubscribed를 사용하십시오. 공유하면 여러 수집기가 구독할 때 업스트림이 중복 실행되는 것을 막을 수 있습니다.
자주 묻는 질문
“shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기” 강의는 무료인가요?
네 — “shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Kotlin Academy 강의 전체를 잠금 해제할 수 있습니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기”에서 뭘 배우나요?
공유 연산자로 콜드 Flow를 핫 스트림으로 변환해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Kotlin Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Kotlin Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Kotlin Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Kotlin Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Kotlin Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- StateFlow: UI를 위한 핫 상태 보유자
- SharedFlow: 이벤트 버스와 일회성 이벤트
- shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기
- Turbine으로 StateFlow와 SharedFlow 테스트하기