shareIn converts a cold Flow into a hot shared flow so multiple collectors receive the same emissions instead of independently repeating sensor queries, network requests, database queries, or long-running computations. It launches collection in the supplied CoroutineScope and uses a SharingStarted strategy to decide when collection begins. section 16.3.1
Share one temperature stream
fun main() { val temps = getTemperatures() runBlocking { val sharedTemps = temps.shareIn(this, SharingStarted.Lazily) launch { sharedTemps.collect { log("$it Celsius") } } launch { sharedTemps.collect { log("${celsiusToFahrenheit(it)} Fahrenheit") } } } } Here, getTemperatures() supplies one cold flow. shareIn(this, SharingStarted.Lazily) starts sharing within runBlocking's scope when the first subscriber appears. Both collectors then observe the same temperature emissions while formatting them differently. section 16.3.1
The SharingStarted argument controls when the shared collection runs:
- Eagerly starts collection immediately. section 16.3.1
- Lazily waits until the first subscriber appears. section 16.3.1
- WhileSubscribed starts with the first subscriber and manages collection around subscriber presence. section 16.3.1
Figure 16.5 Shared flows operate in a broadcast fashion. When an element is emitted into the shared flow, all subscribers currently collecting the flow will receive this emission.
Use the broadcast diagram to see why each currently collecting subscriber receives an emitted shared-flow value. section 16.3.1
