liveBook · Manning

shareIn

As explained in Kotlin in Action, 2E

shareIn is a kotlinx.coroutines Flow operation that converts a cold flow into a hot shared flow within a specified coroutine scope.

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.
CH16_F05_Isakova

Use the broadcast diagram to see why each currently collecting subscriber receives an emitted shared-flow value. section 16.3.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains cold-to-hot conversion, coroutine scope, start strategies, and a runnable temperature example, but not implementation internals.
Examples
Uses a temperature sensor flow collected as Celsius and Fahrenheit, with lazy sharing and concurrent collectors.
What it assumes
Assumes familiarity with Flow collection, coroutines, CoroutineScope, launch, and cold-versus-hot flow behavior.
What you can do after
Apply it via kotlinx.coroutines to broadcast one cold-flow execution to multiple collectors.
How it connects
Connects cold flows with hot flows, shared flows, subscribers, collectors, and CoroutineScope.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.