collectAsReceiver

suspend fun <T> Flow<T>.collectAsReceiver(block: suspend ChannelReceiverContext<T>.() -> Unit)

Collects the items emitted by this Flow into a ChannelReceiverContext and applies the given block to it.

This function launches a new coroutine in the current CoroutineScope in which the given block is executed. The block is provided with a ChannelReceiverContext that it can use to receive items from the Flow. Once all items have been collected, the ChannelReceiverContext is marked as completed and the coroutine is joined.

Parameters

block

The block to apply to the ChannelReceiverContext.

Example usage:

val flow = flowOf(1, 2, 3, 4, 5)

flow.collectAsReceiver {
while (true) {
val items = next(3)
println(items)
}

// Prints: [1, 2, 3] and then [4, 5]
}

suspend fun <T> Flow<T>.collectAsReceiver(scope: CoroutineScope = CoroutineScope(Dispatchers.Default), block: suspend ChannelReceiverContext<T>.() -> Unit)

Collects the items emitted by this Flow into a ChannelReceiverContext and applies the given block to it.

This function launches a new coroutine in the current CoroutineScope in which the given block is executed. The block is provided with a ChannelReceiverContext that it can use to receive items from the Flow. Once all items have been collected, the ChannelReceiverContext is marked as completed and the coroutine is joined.

Parameters

block

The block to apply to the ChannelReceiverContext.

Example usage:

val flow = flowOf(1, 2, 3, 4, 5)
flow.collectAsReceiver {
while (true) {
val items = next(3)
println(items)
}

// Prints: [1, 2, 3] and then [4, 5]
}