Skip to content

Instantly share code, notes, and snippets.

@AndroidPoet
Last active November 25, 2024 07:30
Show Gist options
  • Save AndroidPoet/90dcb0d44db8a646e7011a4ea149225f to your computer and use it in GitHub Desktop.
Save AndroidPoet/90dcb0d44db8a646e7011a4ea149225f to your computer and use it in GitHub Desktop.

Kotlin Flow Cheat Sheet

Flow Types

Flow Type Purpose Key Features Use Case
flow {} Creates a cold flow that emits values lazily. Emits values only when collected.
Supports suspending functions.
Creating custom flows to emit data on demand.
flowOf() Creates a flow from a fixed set of values. Emits provided values sequentially.
Cold by nature.
Emit predefined values (e.g., configuration settings).
asFlow() Converts collections, sequences, arrays, or ranges to flows. Supports many standard types.
Cold by nature.
Convert lists or arrays into flows for processing.
callbackFlow Creates a cold flow where values are sent from external callbacks. Provides a SendChannel for emitting values.
Handles resource cleanup with awaitClose.
Listening to asynchronous updates like location changes or socket events.
channelFlow Creates a cold flow with concurrent emissions sent to a Channel. Emits values concurrently.
Supports suspending functions.
Handles cleanup with awaitClose.
Concurrently emitting values, such as fetching multiple resources in parallel.
emptyFlow() Creates an empty flow that emits no values. Emits no values and completes immediately.
Useful for testing.
Use as a placeholder flow that emits nothing.

Intermediate Operators

Operator Purpose Key Features Use Case
map Transforms each emitted value. Applies a function to each value. Convert raw data into usable formats (e.g., map Int to String).
filter Filters out unwanted values. Emits only values that satisfy the predicate. Remove irrelevant data from a flow (e.g., filter invalid entries).
flatMapConcat Transforms each value into a flow and processes them sequentially. Processes flows one at a time.
Sequential ordering is guaranteed.
Fetch paginated data where order matters.
flatMapMerge Transforms each value into a flow and processes them concurrently. Processes multiple flows in parallel.
Emits as soon as results are available.
Fetch weather data for multiple cities concurrently.
flatMapLatest Cancels the previous flow when a new value is emitted. Only the most recent value is processed.
Ideal for real-time scenarios.
Real-time search where only the latest input is relevant.
combine Combines multiple flows into a single flow. Emits values whenever any of the flows emit.
Combines their latest values.
Display combined user preferences and weather updates.
zip Combines flows pair-wise, emitting only when all flows emit. Pairs values from two flows.
Completes when any flow finishes.
Pair user actions with corresponding API responses.
distinctUntilChanged Filters out consecutive duplicate values. Emits only when the value changes.
Prevents redundant emissions.
Avoid unnecessary UI updates when the state hasn't changed.
onStart Executes an action before the flow starts emitting. Useful for logging or emitting initial values.
Similar to onEach.
Log when the flow begins or emit a loading indicator.
onCompletion Executes an action after the flow completes. Captures exceptions that cause completion.
Useful for cleanup.
Release resources or log completion success.
onEmpty Executes an action when the flow completes without emitting values. Emits additional values if needed.
Useful for handling empty flows.
Emit fallback data or log when no data is emitted.

Terminal Operators

Operator Purpose Key Features Use Case
collect Collects values from the flow, triggering its execution. Terminal operator.
Executes the flow logic.
Print or use emitted data in business logic.
collectLatest Collects the latest value, cancelling the previous one if a new value is emitted. Cancels ongoing collection for prior values.
Ideal for high-frequency updates.
Handle rapid updates like real-time search.
launchIn Collects the flow in the provided coroutine scope. Shorthand for scope.launch { flow.collect() }.
Tied to coroutine lifecycle.
Launch and collect flows in a specific scope.
first Returns the first emitted value and cancels the flow. Stops the flow after the first emission. Fetch the first available record (e.g., first page of data).
firstOrNull Returns the first emitted value or null if the flow is empty. Gracefully handles empty flows. Handle optional results.
toList / toSet Collects the flow into a list or set. Converts emitted values to a collection. Aggregate all emitted data into a collection.
reduce Reduces a flow to a single value using an accumulator function. Throws an error if the flow is empty. Calculate cumulative results (e.g., sum or product).
fold Similar to reduce, but starts with an initial value. Operates on empty flows.
Includes an initial value.
Aggregate values with an initial base value.

Error Handling

Operator Purpose Key Features Use Case
catch Handles exceptions that occur during flow collection. Captures upstream errors.
Does not interfere with downstream collectors.
Log or recover from errors while keeping the flow operational.
retry Retries the flow on exceptions. Configurable retry logic.
Handles transient errors.
Handle network errors or retry API calls.
retryWhen Retries the flow based on a custom predicate when an exception occurs. Provides retry attempt count.
Access to exception details.
Retry on specific errors (e.g., HTTP 500).

Advanced Flow Types

Type Purpose Key Features Use Case
StateFlow Hot flow that holds a single latest value. Always holds a value.
Emitters update the state.
Manage state in ViewModels (e.g., selected city or current user).
SharedFlow Hot flow that emits values to multiple collectors. Shares values among multiple collectors.
Can replay previous values.
Emit events to multiple subscribers (e.g., notifications or live updates).
stateIn Converts a cold flow into a hot StateFlow. Shares the latest value among subscribers.
Requires a coroutine scope.
Maintain a single source of truth for UI state.
shareIn Converts a cold flow into a hot SharedFlow. Shares emissions with multiple collectors.
Hot by nature.
Broadcast events to multiple subscribers.
debounce Emits values after a delay, ignoring quick subsequent emissions. Reduces frequency of emissions.
Often used with user input.
Debounce search input to prevent excessive API calls.
buffer Buffers emitted values to improve performance. Stores a buffer of values in memory.
Prevents backpressure issues.
Optimize flows that produce data faster than they can be consumed.
timeout Emits a TimeoutCancellationException if no values are emitted within the specified time. Prevents indefinite stalling.
Configurable timeout logic.
Set time limits for receiving data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment