Skip to main content

Crate coroflow

Crate coroflow 

Source
Expand description

§coroflow

coroflow provides structured coroutines, jobs, dispatchers, channels, and Kotlin-style Flow operators for Rust. Native targets use thread pools and a timer thread; browser builds use the page event loop. A custom executor implements Dispatch.

Depend directly on coroflow for async tasks or streams outside Cranpose. Use cranpose-coroflow for view models and composition-aware collection. The feature set is empty.

§Collect a flow

flow_of creates a finite stream. run_test supplies virtual time and waits for the test body and child tasks:

use coroflow::{FlowExt, flow_of, run_test};

let result = run_test(async |_| {
    flow_of(vec![1, 2, 3])
        .map(|value| value * 2)
        .to_vec()
        .await
});

assert_eq!(result, Ok(vec![2, 4, 6]));

§Kotlin API map

KotlinRust API
CoroutineScope, launch, asyncCoroutineScope, Scope::launch, Scope::async_
Dispatchers.Default, Dispatchers.IO, Dispatchers.MainDispatchers::default_pool, Dispatchers::io, ConfinedDispatcher
delay, withContext, withTimeoutOrNulldelay, with_context, with_timeout
Flow, flow {}, flowOfFlow, flow, flow_of
map, filter, combine, flatMapLatestFlowExt, combine3, combine_all
Channel, channelFlow, callbackFlowchannel, channel_flow, callback_flow
MutableStateFlow, MutableSharedFlowMutableStateFlow, MutableSharedFlow
map, filter, mapNotNull, scan, drop, debounce, zip, combine, flowOnFlowExt
flatMapLatest, flatMapConcat, flatMapMerge, catch, retry, retryWhenFlowExt
sample, timeout, onEmpty, withIndex, distinctUntilChangedBy, runningReduce, chunkedFlowExt
launchIn, produceIn, fold, reduceOrNull, count, lastOrNull, singleOrNullFlowExt
Async flow transformationsmap_async, filter_async, filter_map_async, on_each_async, collect_async
Multi-flow operationsmerge, combine3, combine4, combine5, combine_all
SynchronizationMutex, Semaphore, channel
runTest and Turbinerun_test, TestScheduler, Turbine

Flow operators are structs. A chain stores operator state once per collection. Rust cancels a coroutine when its future drops. Background scopes require Send captures; main-thread scopes stay thread-confined.

§Native worker budgets

Dispatchers::default_pool() and Dispatchers::io() use lazy worker pools with coordinated limits and separate queues. Each lane can run up to the device’s available parallelism; their combined worker limit is twice that value. Blocked I/O leaves capacity for CPU work. Workers retire after 30 idle seconds and release their thread-local resources. Getting a dispatcher without submitting work starts no worker threads.

Use DispatcherPool::new(DispatcherPoolConfig { ..Default::default() }) for an owned pair with different CPU/I/O limits or an idle timeout. Its cpu() and io() handles keep the pool alive independently. Dispatchers::single_thread starts its dedicated thread on first use and preserves that thread’s identity until the dispatcher is no longer used.

Coroutine wake-ups are never rejected for overload. The limits bound executing steps and worker threads; queued steps and suspended futures still retain data. Bound producer concurrency with structured scopes, channels or semaphores when launching large batches. Cancellation drops a future on its dispatcher and cannot interrupt an already-running blocking call. Browser dispatchers use the page event loop, where blocking code remains unsuitable.

Cranpose’s withBlocking executor has its own bounded queue and worker budget. These coroutine limits do not change that executor or require a context parameter in composables.

Structs§

AwaitAll
The future returned by await_all.
BoxFlow
A type-erased, shareable Flow that can cross threads.
Buffered
The flow returned by flow_on, buffer and conflate: the upstream runs in its own coroutine and hands values over through a channel.
BufferedRun
One run of a Buffered; the upstream starts on the first poll and is cancelled when the run is dropped.
Catch
The flow returned by catch.
CatchRun
One run of a Catch.
ChannelFlow
The flow returned by channel_flow.
ChannelFlowRun
One run of a ChannelFlow; dropping it cancels its producers.
ChildFailed
A child of a coroutine_scope panicked, so the scope cancelled its other work.
Chunked
The flow returned by chunked.
ChunkedRun
One run of a Chunked.
Collect
The future returned by collect.
Combine
The flow returned by combine.
Combine3
The flow returned by combine3.
Combine4
The flow returned by combine4.
Combine5
The flow returned by combine5.
Combine3Run
One run of a Combine3.
Combine4Run
One run of a Combine4.
Combine5Run
One run of a Combine5.
CombineAll
The flow returned by combine_all.
CombineAllRun
One run of a CombineAll.
CombineRun
One run of a Combine.
ConfinedDispatcher
A Dispatcher whose executor runs everything on the thread that created this handle — Kotlin’s Dispatchers.Main.
CustomSharing
A strategy made by SharingStarted::custom.
Debounce
The flow returned by debounce.
DebounceRun
One run of a Debounce.
Deferred
The result of a coroutine started with async_ — Kotlin’s Deferred.
Delay
The future returned by delay.
Dispatcher
Where coroutines run and which Clock they measure time with.
DispatcherPool
CPU and I/O dispatchers with coordinated, demand-driven worker budgets.
DispatcherPoolConfig
Concurrency and retention limits for a DispatcherPool.
Dispatchers
The shared dispatchers every application gets — Kotlin’s Dispatchers.
DistinctRun
One run of a DistinctUntilChanged.
DistinctUntilChanged
The flow returned by distinct_until_changed and distinct_until_changed_by.
Emit
The future returned by Emitter::emit.
EmitShared
The future returned by MutableSharedFlow::emit.
Emitter
The handle a flow block emits values through — Kotlin’s FlowCollector.
EmitterAction
The step whose action gets only an Emitter: the fallback of on_empty and the prelude of on_subscription.
Emitting
The step that hands each value and an Emitter to an action, and completes the flow when the action’s Verdict says not to go on.
Filter
The flow returned by filter.
FilterMap
The flow returned by filter_map.
FilterMapRun
One run of a FilterMap.
FilterMapping
The step of filter_map_async.
FilterRun
One run of a Filter.
First
The future returned by first.
FirstState
The coroutine behind state_in_first: it waits for the upstream’s first value, hands over a state holding it, and keeps the state up to date.
FlatMap
The flow returned by flat_map_latest, flat_map_merge and flat_map_concat.
FlatMapRun
One run of a FlatMap.
FlowBlock
The flow returned by flow.
FlowBlockRun
One run of a FlowBlock.
FlowOf
The flow returned by flow_of.
FlowOfRun
One run of a FlowOf.
Fold
The future returned by fold, count and last.
InOrder
Runs the action for one value at a time, in order.
Job
A handle to one launched coroutine — Kotlin’s Job.
Join
The future returned by Job::join.
LatestOnly
Cancels the running action as soon as a newer value arrives — Kotlin’s *Latest operators.
LocalBoxFlow
A type-erased Flow confined to one thread, for flows that capture Rc or other thread-bound values.
Map
The flow returned by map.
MapRun
One run of a Map.
Mapping
The step of map_async, map_latest, collect_async and collect_latest.
Merge
The flow returned by merge.
MergeRun
One run of a Merge.
MutableSharedFlow
A hot broadcast of values to every current collector — Kotlin’s MutableSharedFlow.
MutableStateFlow
A hot, observable holder of one value — Kotlin’s MutableStateFlow.
Mutex
Mutual exclusion a coroutine may hold across suspension points — Kotlin’s Mutex, guarding the value it owns the way std::sync::Mutex does.
MutexGuard
Exclusive access to the value of a Mutex; dropping it unlocks.
OnCompletion
The flow returned by on_completion.
OnCompletionRun
One run of an OnCompletion; its action runs when the run ends or is dropped.
OnEach
The flow returned by on_each.
OnEachRun
One run of an OnEach.
OnEmpty
The flow returned by on_empty.
OnEmptyRun
One run of an OnEmpty.
OnStart
The flow returned by on_start.
OnSubscription
The flow returned by SharedFlow::on_subscription.
OnSubscriptionRun
One run of an OnSubscription.
Passing
The step that runs an action on a clone of each value and emits the value when the action’s Verdict keeps it.
Permit
A permit taken from a Semaphore; dropping it gives the permit back.
ProduceIn
The coroutine produce_in launches: it collects a flow into a channel until the flow ends or every receiver is gone.
Producer
The sending side handed to a channel_flow block.
Receiver
The receiving end of a channel; it is also a hot Flow whose collectors share the values — Kotlin’s receiveAsFlow().
RecvFuture
The future returned by Receiver::recv.
Reduce
The future returned by reduce.
RetryRun
One run of a RetryWhen.
RetryWhen
The flow returned by retry_when.
Runnable
One scheduled step of a coroutine, handed to a Dispatch implementation.
RunningReduce
The flow returned by running_reduce.
RunningReduceRun
One run of a RunningReduce.
Sample
The flow returned by sample.
SampleRun
One run of a Sample.
Scan
The flow returned by scan.
ScanRun
One run of a Scan.
Scope
Owns coroutines launched on a dispatcher of type D — Kotlin’s CoroutineScope with a SupervisorJob.
ScopeHandle
A weak handle to a CoroutineScope, see Scope::handle.
Select
The future returned by select.
SelectAll
The future returned by select_all.
Semaphore
Limits how many coroutines run a section at once — Kotlin’s Semaphore.
SendError
The channel was closed, or every receiver is gone; the value comes back.
SendFuture
The future returned by Sender::send.
Sender
The sending end of a channel.
SharedFlow
The read-only side of a MutableSharedFlow — Kotlin’s SharedFlow.
SharedRun
One subscription to a SharedFlow; dropping it unsubscribes.
SharingTask
The coroutine behind state_in and share_in: it watches the collector count of target and starts or stops the upstream.
Single
The future returned by single.
Skip
The flow returned by skip.
SkipRun
One run of a Skip.
Skipping
Ignores values while the predicate holds, then emits everything — the skip_while kind of While.
Stalled
A TestScheduler ran out of work before the future it drives finished.
StartWith
The flow returned by start_with.
StartWithRun
One run of a StartWith.
StateFlow
The read-only side of a MutableStateFlow — Kotlin’s StateFlow.
StateInFirst
The future returned by state_in_first: the state once the upstream emitted, or None if it completed without a value.
StateRun
One subscription to a StateFlow; dropping it unsubscribes.
Suspending
A flow whose operator runs a suspending action per value; see Step.
SuspendingRun
One run of a Suspending flow.
SystemClock
The wall-clock Clock used by Dispatchers.
Take
The flow returned by take.
TakeRun
One run of a Take.
Taking
Emits values while the predicate holds, then completes — the take_while kind of While.
TaskFailed
The coroutine switched to another dispatcher ended without a result because it panicked or its dispatcher dropped it.
TestScheduler
A deterministic, single-threaded scheduler with virtual time — Kotlin’s StandardTestDispatcher plus runTest.
TestScope
What run_test hands its body — Kotlin’s TestScope.
TimedOut
The work given to with_timeout did not finish in time.
Timeout
The flow returned by timeout.
TimeoutRun
One run of a Timeout.
ToVec
The future returned by to_vec.
Turbine
Steps through a flow by hand in a test — Kotlin’s Turbine.
While
The flow returned by take_while and skip_while.
WhileRun
One run of a While.
WholeValue
Compares whole values — plain distinct_until_changed.
WithContext
The future returned by with_context.
WithIndex
The flow returned by with_index.
WithIndexRun
One run of a WithIndex.
WithTimeout
The future returned by with_timeout.
YieldNow
The future returned by yield_now.
Zip
The flow returned by zip.
ZipRun
One run of a Zip.

Enums§

BufferOverflow
What a MutableSharedFlow does when an emission finds collectors too far behind — Kotlin’s BufferOverflow.
Capacity
How many values a channel holds before send waits — Kotlin’s channel capacities.
Either
One of two results.
Finish
What a suspending operator does once its action for one value finished.
JobOutcome
How a coroutine finished.
SharingCommand
What a custom SharingStarted strategy tells the sharing coroutine — Kotlin’s SharingCommand.
SharingStarted
When a shared flow runs its upstream — Kotlin’s SharingStarted.
TryRecvError
Why Receiver::try_recv returned no value.
TrySendError
Why Sender::try_send could not send; the value comes back.

Constants§

DEFAULT_CONCURRENCY
Kotlin’s default number of inner flows FlowExt::flat_map_merge and FlowExt::flatten_merge collect at once.
FLOW_ON_BUFFER
How many values flow_on buffers between the upstream’s dispatcher and the collector — Kotlin’s default channel size.
SHARE_IN_BUFFER
The smallest buffer share_in gives collectors that fall behind, replay included — Kotlin’s default channel size. Beyond it the upstream waits.

Traits§

ChangeKey
How DistinctUntilChanged decides that a value changed: by the whole value (WholeValue) or by a key closure Fn(&T) -> K.
Clock
A monotonic time source that can wake a task at a deadline.
Dispatch
Runs scheduled coroutine steps somewhere: a thread pool, a UI event loop or a test queue.
Flow
A cold, re-runnable asynchronous sequence — Kotlin’s Flow.
FlowExt
Operators and terminal operations available on every Flow.
Order
How a Suspending flow schedules its actions: InOrder or LatestOnly.
SendFlow
A Flow that background scopes can run — what data and domain layers return as impl SendFlow<Item = T>.
Spawn
Something coroutines of type F can be launched into.
Step
How one suspending operator calls its action and what it emits.
Stream
A stream of values produced asynchronously.
Verdict
What a suspending action’s result says about its value: bool keeps the value when true, and () always keeps it.

Functions§

await_all
Waits for every deferred value and returns them in order, or the first failure as soon as it happens — Kotlin’s awaitAll.
callback_flow
A cold flow whose values a coroutine sends through a channel — Kotlin’s channelFlow.
channel
Creates a channel — Kotlin’s Channel(capacity).
channel_flow
A cold flow whose values a coroutine sends through a channel — Kotlin’s channelFlow.
combine3
Combines the latest values of three flows once each has emitted — Kotlin’s combine.
combine4
Combines the latest values of four flows once each has emitted — Kotlin’s combine.
combine5
Combines the latest values of five flows once each has emitted — Kotlin’s combine.
combine_all
Combines the latest values of every flow in flows once each has emitted, handing them to combiner in order — Kotlin’s combine(flows) { values -> }.
coroutine_scope
Runs block with a scope for child coroutines and returns once block and every child have finished — Kotlin’s coroutineScope.
delay
Suspends the calling coroutine for duration — Kotlin’s delay.
flow
Builds a cold flow from an async block — Kotlin’s flow { emit(x) }.
flow_of
A cold flow that emits clones of items on every collection — Kotlin’s flowOf.
join_all
Waits until every job in jobs has finished — Kotlin’s joinAll.
merge
Emits the values of all flows as they arrive, completing once every one has completed — Kotlin’s merge.
produce
Launches block in scope with the sending end of a new channel and returns the receiving end — Kotlin’s produce. The channel closes when block and every sender it handed out are done.
run_test
Runs a test body on virtual time and returns its result — Kotlin’s runTest.
select
Waits for whichever of two futures finishes first and drops the other — Kotlin’s select, biased towards first when both are ready.
select_all
Waits for the first of futures to finish and returns its index and output, dropping the rest — biased towards earlier futures.
supervisor_scope
Like coroutine_scope, but a failing child does not cancel block or its siblings — Kotlin’s supervisorScope.
with_context
Runs future on dispatcher and waits for its result — Kotlin’s withContext.
with_timeout
Runs future, giving up after timeout — Kotlin’s withTimeoutOrNull.
yield_now
Lets other coroutines on the same dispatcher run before continuing — Kotlin’s yield.

Type Aliases§

BoxFuture
The result of a suspend fun declared on a trait object: a boxed future that background dispatchers can run.
CollectAsync
The future returned by collect_async.
CollectLatest
The future returned by collect_latest.
CoroutineScope
A scope for background work: every launched future must be Send.
Count
The future returned by count.
Filtering
The step of filter_async.
Flatten
The flow returned by flatten_concat and flatten_merge.
Inspecting
The step of on_each_async.
Last
The future returned by last.
MainScope
A scope confined to the main thread — Kotlin’s viewModelScope.
Transforming
The step of transform and transform_latest.
TransformingWhile
The step of transform_while.