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
| Kotlin | Rust API |
|---|---|
CoroutineScope, launch, async | CoroutineScope, Scope::launch, Scope::async_ |
Dispatchers.Default, Dispatchers.IO, Dispatchers.Main | Dispatchers::default_pool, Dispatchers::io, ConfinedDispatcher |
delay, withContext, withTimeoutOrNull | delay, with_context, with_timeout |
Flow, flow {}, flowOf | Flow, flow, flow_of |
map, filter, combine, flatMapLatest | FlowExt, combine3, combine_all |
Channel, channelFlow, callbackFlow | channel, channel_flow, callback_flow |
MutableStateFlow, MutableSharedFlow | MutableStateFlow, MutableSharedFlow |
map, filter, mapNotNull, scan, drop, debounce, zip, combine, flowOn | FlowExt |
flatMapLatest, flatMapConcat, flatMapMerge, catch, retry, retryWhen | FlowExt |
sample, timeout, onEmpty, withIndex, distinctUntilChangedBy, runningReduce, chunked | FlowExt |
launchIn, produceIn, fold, reduceOrNull, count, lastOrNull, singleOrNull | FlowExt |
| Async flow transformations | map_async, filter_async, filter_map_async, on_each_async, collect_async |
| Multi-flow operations | merge, combine3, combine4, combine5, combine_all |
| Synchronization | Mutex, Semaphore, channel |
runTest and Turbine | run_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§
- Await
All - The future returned by
await_all. - BoxFlow
- A type-erased, shareable
Flowthat can cross threads. - Buffered
- The flow returned by
flow_on,bufferandconflate: the upstream runs in its own coroutine and hands values over through a channel. - Buffered
Run - 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. - Catch
Run - One run of a
Catch. - Channel
Flow - The flow returned by
channel_flow. - Channel
Flow Run - One run of a
ChannelFlow; dropping it cancels its producers. - Child
Failed - A child of a
coroutine_scopepanicked, so the scope cancelled its other work. - Chunked
- The flow returned by
chunked. - Chunked
Run - 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. - Combine3
Run - One run of a
Combine3. - Combine4
Run - One run of a
Combine4. - Combine5
Run - One run of a
Combine5. - Combine
All - The flow returned by
combine_all. - Combine
AllRun - One run of a
CombineAll. - Combine
Run - One run of a
Combine. - Confined
Dispatcher - A
Dispatcherwhose executor runs everything on the thread that created this handle — Kotlin’sDispatchers.Main. - Custom
Sharing - A strategy made by
SharingStarted::custom. - Debounce
- The flow returned by
debounce. - Debounce
Run - One run of a
Debounce. - Deferred
- The result of a coroutine started with
async_— Kotlin’sDeferred. - Delay
- The future returned by
delay. - Dispatcher
- Where coroutines run and which
Clockthey measure time with. - Dispatcher
Pool - CPU and I/O dispatchers with coordinated, demand-driven worker budgets.
- Dispatcher
Pool Config - Concurrency and retention limits for a
DispatcherPool. - Dispatchers
- The shared dispatchers every application gets — Kotlin’s
Dispatchers. - Distinct
Run - One run of a
DistinctUntilChanged. - Distinct
Until Changed - The flow returned by
distinct_until_changedanddistinct_until_changed_by. - Emit
- The future returned by
Emitter::emit. - Emit
Shared - The future returned by
MutableSharedFlow::emit. - Emitter
- The handle a
flowblock emits values through — Kotlin’sFlowCollector. - Emitter
Action - The step whose action gets only an
Emitter: the fallback ofon_emptyand the prelude ofon_subscription. - Emitting
- The step that hands each value and an
Emitterto an action, and completes the flow when the action’sVerdictsays not to go on. - Filter
- The flow returned by
filter. - Filter
Map - The flow returned by
filter_map. - Filter
MapRun - One run of a
FilterMap. - Filter
Mapping - The step of
filter_map_async. - Filter
Run - One run of a
Filter. - First
- The future returned by
first. - First
State - 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_mergeandflat_map_concat. - Flat
MapRun - One run of a
FlatMap. - Flow
Block - The flow returned by
flow. - Flow
Block Run - One run of a
FlowBlock. - FlowOf
- The flow returned by
flow_of. - Flow
OfRun - One run of a
FlowOf. - Fold
- The future returned by
fold,countandlast. - 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. - Latest
Only - Cancels the running action as soon as a newer value arrives — Kotlin’s
*Latestoperators. - Local
BoxFlow - A type-erased
Flowconfined to one thread, for flows that captureRcor 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_asyncandcollect_latest. - Merge
- The flow returned by
merge. - Merge
Run - One run of a
Merge. - Mutable
Shared Flow - A hot broadcast of values to every current collector — Kotlin’s
MutableSharedFlow. - Mutable
State Flow - 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 waystd::sync::Mutexdoes. - Mutex
Guard - Exclusive access to the value of a
Mutex; dropping it unlocks. - OnCompletion
- The flow returned by
on_completion. - OnCompletion
Run - One run of an
OnCompletion; its action runs when the run ends or is dropped. - OnEach
- The flow returned by
on_each. - OnEach
Run - One run of an
OnEach. - OnEmpty
- The flow returned by
on_empty. - OnEmpty
Run - One run of an
OnEmpty. - OnStart
- The flow returned by
on_start. - OnSubscription
- The flow returned by
SharedFlow::on_subscription. - OnSubscription
Run - 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
Verdictkeeps it. - Permit
- A permit taken from a
Semaphore; dropping it gives the permit back. - Produce
In - The coroutine
produce_inlaunches: it collects a flow into a channel until the flow ends or every receiver is gone. - Producer
- The sending side handed to a
channel_flowblock. - Receiver
- The receiving end of a
channel; it is also a hotFlowwhose collectors share the values — Kotlin’sreceiveAsFlow(). - Recv
Future - The future returned by
Receiver::recv. - Reduce
- The future returned by
reduce. - Retry
Run - One run of a
RetryWhen. - Retry
When - The flow returned by
retry_when. - Runnable
- One scheduled step of a coroutine, handed to a
Dispatchimplementation. - Running
Reduce - The flow returned by
running_reduce. - Running
Reduce Run - One run of a
RunningReduce. - Sample
- The flow returned by
sample. - Sample
Run - 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’sCoroutineScopewith aSupervisorJob. - Scope
Handle - A weak handle to a
CoroutineScope, seeScope::handle. - Select
- The future returned by
select. - Select
All - The future returned by
select_all. - Semaphore
- Limits how many coroutines run a section at once — Kotlin’s
Semaphore. - Send
Error - The channel was closed, or every receiver is gone; the value comes back.
- Send
Future - The future returned by
Sender::send. - Sender
- The sending end of a
channel. - Shared
Flow - The read-only side of a
MutableSharedFlow— Kotlin’sSharedFlow. - Shared
Run - One subscription to a
SharedFlow; dropping it unsubscribes. - Sharing
Task - The coroutine behind
state_inandshare_in: it watches the collector count oftargetand 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_whilekind ofWhile. - Stalled
- A
TestSchedulerran out of work before the future it drives finished. - Start
With - The flow returned by
start_with. - Start
With Run - One run of a
StartWith. - State
Flow - The read-only side of a
MutableStateFlow— Kotlin’sStateFlow. - State
InFirst - The future returned by
state_in_first: the state once the upstream emitted, orNoneif it completed without a value. - State
Run - One subscription to a
StateFlow; dropping it unsubscribes. - Suspending
- A flow whose operator runs a suspending action per value; see
Step. - Suspending
Run - One run of a
Suspendingflow. - System
Clock - The wall-clock
Clockused byDispatchers. - Take
- The flow returned by
take. - TakeRun
- One run of a
Take. - Taking
- Emits values while the predicate holds, then completes — the
take_whilekind ofWhile. - Task
Failed - The coroutine switched to another dispatcher ended without a result because it panicked or its dispatcher dropped it.
- Test
Scheduler - A deterministic, single-threaded scheduler with virtual time — Kotlin’s
StandardTestDispatcherplusrunTest. - Test
Scope - What
run_testhands its body — Kotlin’sTestScope. - Timed
Out - The work given to
with_timeoutdid not finish in time. - Timeout
- The flow returned by
timeout. - Timeout
Run - 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_whileandskip_while. - While
Run - One run of a
While. - Whole
Value - Compares whole values — plain
distinct_until_changed. - With
Context - The future returned by
with_context. - With
Index - The flow returned by
with_index. - With
Index Run - One run of a
WithIndex. - With
Timeout - The future returned by
with_timeout. - Yield
Now - The future returned by
yield_now. - Zip
- The flow returned by
zip. - ZipRun
- One run of a
Zip.
Enums§
- Buffer
Overflow - What a
MutableSharedFlowdoes when an emission finds collectors too far behind — Kotlin’sBufferOverflow. - Capacity
- How many values a channel holds before
sendwaits — 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.
- Sharing
Command - What a custom
SharingStartedstrategy tells the sharing coroutine — Kotlin’sSharingCommand. - Sharing
Started - When a shared flow runs its upstream — Kotlin’s
SharingStarted. - TryRecv
Error - Why
Receiver::try_recvreturned no value. - TrySend
Error - Why
Sender::try_sendcould not send; the value comes back.
Constants§
- DEFAULT_
CONCURRENCY - Kotlin’s default number of inner flows
FlowExt::flat_map_mergeandFlowExt::flatten_mergecollect at once. - FLOW_
ON_ BUFFER - How many values
flow_onbuffers between the upstream’s dispatcher and the collector — Kotlin’s default channel size. - SHARE_
IN_ BUFFER - The smallest buffer
share_ingives collectors that fall behind, replay included — Kotlin’s default channel size. Beyond it the upstream waits.
Traits§
- Change
Key - How
DistinctUntilChangeddecides that a value changed: by the whole value (WholeValue) or by a key closureFn(&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
Suspendingflow schedules its actions:InOrderorLatestOnly. - Send
Flow - A
Flowthat background scopes can run — what data and domain layers return asimpl SendFlow<Item = T>. - Spawn
- Something coroutines of type
Fcan 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:
boolkeeps the value whentrue, 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
flowsonce each has emitted, handing them tocombinerin order — Kotlin’scombine(flows) { values -> }. - coroutine_
scope - Runs
blockwith a scope for child coroutines and returns onceblockand every child have finished — Kotlin’scoroutineScope. - delay
- Suspends the calling coroutine for
duration— Kotlin’sdelay. - flow
- Builds a cold flow from an async block — Kotlin’s
flow { emit(x) }. - flow_of
- A cold flow that emits clones of
itemson every collection — Kotlin’sflowOf. - join_
all - Waits until every job in
jobshas finished — Kotlin’sjoinAll. - merge
- Emits the values of all
flowsas they arrive, completing once every one has completed — Kotlin’smerge. - produce
- Launches
blockinscopewith the sending end of a new channel and returns the receiving end — Kotlin’sproduce. The channel closes whenblockand 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 towardsfirstwhen both are ready. - select_
all - Waits for the first of
futuresto 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 cancelblockor its siblings — Kotlin’ssupervisorScope. - with_
context - Runs
futureondispatcherand waits for its result — Kotlin’swithContext. - with_
timeout - Runs
future, giving up aftertimeout— Kotlin’swithTimeoutOrNull. - yield_
now - Lets other coroutines on the same dispatcher run before continuing —
Kotlin’s
yield.
Type Aliases§
- BoxFuture
- The result of a
suspend fundeclared on a trait object: a boxed future that background dispatchers can run. - Collect
Async - The future returned by
collect_async. - Collect
Latest - The future returned by
collect_latest. - Coroutine
Scope - 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_concatandflatten_merge. - Inspecting
- The step of
on_each_async. - Last
- The future returned by
last. - Main
Scope - A scope confined to the main thread — Kotlin’s
viewModelScope. - Transforming
- The step of
transformandtransform_latest. - Transforming
While - The step of
transform_while.