Sobes.tech
Middle

What operators exist in Flow?

sobes.tech AI

Answer from AI

Here are the main Flow operators grouped by categories:

Transformation:

  • map: Applies a transformation function to each value.
  • filter: Filters values that do not match the predicate.
  • take: Takes only the first N values.
  • drop: Skips the first N values.
  • transform: A more flexible operator for transforming from one Flow to another, emitting zero or more values for each input value.

Combining:

  • zip: Combines values from two Flows pairwise.
  • combine: Combines the latest values from two Flows.
  • merge: Merges values from multiple Flows into one.

Flattening:

  • flattenConcat: Concatenates Flows from Flows, processing internal Flows sequentially.
  • flattenMerge: Merges Flows from Flows, processing internal Flows in parallel (with concurrency limit).

Exception Handling:

  • catch: Catches exceptions and performs an action or returns a fallback value.
  • retry: Retries the Flow upon an exception.

Terminal Operators:

  • collect: Collects all values from the Flow.
  • reduce: Aggregates Flow values into one.
  • toList: Converts the Flow into a list.
  • first: Takes only the first value.
  • single: Takes a single value (throws an exception if there is more than one).

Time Operators (often from kotlinx.coroutines.flow.operators):

  • debounce: Emits a value only after a pause in emission.
  • sample: Emits the last value at a specified interval.
  • throttle: Limits the rate of emission of values.

Example of using map:

flowOf(1, 2, 3)
    .map { it * 2 } // Transforms 1, 2, 3 into 2, 4, 6
    .collect { println(it) }

Example of using filter:

flowOf("apple", "banana", "cherry")
    .filter { it.startsWith("b") } // Filters, leaving only "banana"
    .collect { println(it) }

Example of using zip:

val numbers = flowOf(1, 2, 3)
val letters = flowOf("a", "b", "c")

numbers.zip(letters) { number, letter -> "$number$letter" } // Combines into "1a", "2b", "3c"
    .collect { println(it) }