title: Combine multiple Kotlin flows in a list without waiting for a first value
body: <p>I have a <code>List&lt;Flow&lt;T&gt;&gt;</code>, and would like to generate a <code>Flow&lt;List&lt;T&gt;&gt;</code>. This is almost what <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html" rel="noreferrer"><code>combine</code></a> does - except that combine waits for each and every <code>Flow</code> to emit an initial value, which is not what I want. Take this code for example:</p>
  <pre class="lang-kotlin prettyprint-override"><code>val a = flow {
    repeat(3) {
      emit(&quot;a$it&quot;)
      delay(100)
    }
  }
  val b = flow {
    repeat(3) {
      delay(150)
      emit(&quot;b$it&quot;)
    }
  }
  val c = flow {
    delay(400)
    emit(&quot;c&quot;)
  }
  val flows = listOf(a, b, c)
  runBlocking {
    combine(flows) {
      it.toList()
    }.collect { println(it) }
  }
  </code></pre>
  <p>With <code>combine</code> (and hence as-is), this is the output:</p>
  <pre><code>[a2, b1, c]
  [a2, b2, c]
  </code></pre>
  <p>Whereas I'm interested in all the intermediary steps too. This is what I want from those three flows:</p>
  <pre><code>[]
  [a0]
  [a1]
  [a1, b0]
  [a2, b0]
  [a2, b1]
  [a2, b1, c]
  [a2, b2, c]
  </code></pre>
  <p>Right now I have two work-arounds, but none of them are great... The first one is plain ugly and doesn't work with nullable types:</p>
  <pre class="lang-kotlin prettyprint-override"><code>val flows = listOf(a, b, c).map {
    flow {
      emit(null)
      it.collect { emit(it) }
    }
  }
  runBlocking {
    combine(flows) {
      it.filterNotNull()
    }.collect { println(it) }
  }
  </code></pre>
  <p>By forcing all the flows to emit a first, irrelevant value, the <code>combine</code> transformer is indeed called, and lets me remove the null values which I know are not actual values. Iterating on that, more readable but heavier:</p>
  <pre class="lang-kotlin prettyprint-override"><code>sealed class FlowValueHolder {
    object None : FlowValueHolder()
    data class Some&lt;T&gt;(val value: T) : FlowValueHolder()
  }
  val flows = listOf(a, b, c).map {
    flow {
      emit(FlowValueHolder.None)
      it.collect { emit(FlowValueHolder.Some(it)) }
    }
  }
  runBlocking {
    combine(flows) {
      it.filterIsInstance(FlowValueHolder.Some::class.java)
        .map { it.value }
    }.collect { println(it) }
  }
  </code></pre>
  <p>Now this one works just fine, but still feels like I'm overdoing stuff. Is there a method that I'm missing in the coroutines library?</p>