pollWithState

fun <T, S> pollWithState(initial: S, interval: Duration? = null, shouldStop: (S) -> Boolean = { false }, f: suspend (S) -> Pair<S, List<T>>): Flow<T>

Creates a flow that continuously polls elements using the f function, starting with an initial state initial.

The flow stops when the shouldStop function returns true for the current state or when the coroutine context is no longer active.

The primary difference between this function and the regular poll function is that pollWithState maintains state from the previous polling iteration. This can be particularly useful in situations where some level of state control is required, such as HTTP pagination, stream polling, and more.

Return

A Flow of elements of type T, polled by the provided f function.

Example usage:

data class ApiResponse<T>(
val items: List<T>,
val nextPage: Int?
)

suspend fun fetchPage(page: Int): ApiResponse<String> = // Fetch data from some API

pollWithState(
initial = 1, // Initial page number
shouldStop = { it == -1 } // Stop when there are no more pages to fetch
) { currentPage ->
val response = fetchPage(currentPage)
val nextState = response.nextPage
val items = response.items

(nextState ?: -1) to items
}.collect { item -> println(item) }

Parameters

initial

The initial state of type S to begin the polling process.

shouldStop

A predicate function to determine if the polling should stop based on the current state. Defaults to a function that always returns false.

f

A suspending function that takes the current state S as input and returns a pair consisting of the next state S and a list of elements of type T.