subListAsFlow

fun <E> MutableReactiveList<E>.subListAsFlow(fromIndex: Int, toIndex: Int, strict: Boolean = true): Flow<List<E>>

Returns a Flow that emits a sublist view of this reactive list between the specified fromIndex (inclusive) and toIndex (exclusive).

This function observes the reactive list and emits a new sublist snapshot whenever the original list's content changes in a way that affects the sublist. It prevents emissions of identical subsequent sublists.

Behavior Modes

Strict Mode (default: strict = true)

  • Returns an empty list if any index is out of bounds or invalid

  • Validates that 0 <= fromIndex <= toIndex <= list.size

Lenient Mode (strict = false)

  • Automatically coerces indices to valid ranges using coerceIn

  • Useful when you want to observe "as much as possible" of a range

Example:

val numbers = reactiveListOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

// Observe elements from index 2 to 5 (exclusive) in strict mode
numbers.subListAsFlow(2, 5, strict = true).collect { sublist ->
println("Strict sublist [2,5): $sublist")
}

// Observe the same range in lenient mode
numbers.subListAsFlow(2, 5, strict = false).collect { sublist ->
println("Lenient sublist [2,5): $sublist")
}

// Modify the list
delay(1000)
numbers.removeAt(0)
delay(1000)
numbers.retainAll(setOf(2, 3, 4))

// Flow emissions:
// Lenient sublist [2,5): [2, 3, 4]
// Strict sublist [2,5): [2, 3, 4]
// Strict sublist [2,5): [3, 4, 5]
// Lenient sublist [2,5): [3, 4, 5]
// Strict sublist [2,5): []
// Lenient sublist [2,5): [4]

Return

A Flow that emits the specified sublist when the source list changes.

Parameters

E

The type of elements in the list.

fromIndex

The starting index of the sublist (inclusive).

toIndex

The ending index of the sublist (exclusive).

strict

If true (default), an empty list is returned for any invalid indices. This approach avoids exceptions for invalid ranges. If false (lenient mode), indices are safely coerced to the valid range.