(!)
Throws an instance of missionary.Cancelled
if current evaluation context is interrupted, otherwise returns nil. The
evaluation context defaults to the current thread if the host platform supports it, and can be redefined with sp
,
ap
, or cp
.
Throws an instance of `missionary.Cancelled` if current evaluation context is interrupted, otherwise returns nil. The evaluation context defaults to the current thread if the host platform supports it, and can be redefined with `sp`, `ap`, or `cp`.
(? task)
Parks current evaluation context by given task. Evaluation resumes when the task completes, result is returned or
rethrown according to completion status. Interrupting the evaluation context cancels the parking task. The evaluation
context defaults to the current thread if the host platform supports it, and can be redefined with sp
or ap
.
Parks current evaluation context by given task. Evaluation resumes when the task completes, result is returned or rethrown according to completion status. Interrupting the evaluation context cancels the parking task. The evaluation context defaults to the current thread if the host platform supports it, and can be redefined with `sp` or `ap`.
(?< flow)
Forks current evaluation context by given flow. Evaluation resumes whenever the flow transfers, result is returned or
rethrown according to transfer status. Each transfer creates a new processing branch and defines a new evaluation
context inherited from its parent. Concurrent processing branches are not allowed, and the current processing branch is
interrupted when the forking flow becomes ready to transfer again. Interrupting the parent evaluation context cancels
the forking flow and interrupts all processing branches currently being run and those subsequently run. The evaluation
context is undefined by default and can be defined with ap
or cp
.
Example :
(require '[missionary.core :as m])
(import missionary.Cancelled)
(defn debounce [delay flow]
(m/ap (let [x (m/?< flow)]
(try (m/? (m/sleep delay x))
(catch Cancelled _ (m/amb))))))
(m/? (->> (m/ap (let [n (m/amb 24 79 67 34 18 9 99 37)]
(m/? (m/sleep n n))))
(debounce 50)
(m/reduce conj)))
#_=> [24 79 9 37]
Forks current evaluation context by given flow. Evaluation resumes whenever the flow transfers, result is returned or rethrown according to transfer status. Each transfer creates a new processing branch and defines a new evaluation context inherited from its parent. Concurrent processing branches are not allowed, and the current processing branch is interrupted when the forking flow becomes ready to transfer again. Interrupting the parent evaluation context cancels the forking flow and interrupts all processing branches currently being run and those subsequently run. The evaluation context is undefined by default and can be defined with `ap` or `cp`. Example : ```clojure (require '[missionary.core :as m]) (import missionary.Cancelled) (defn debounce [delay flow] (m/ap (let [x (m/?< flow)] (try (m/? (m/sleep delay x)) (catch Cancelled _ (m/amb)))))) (m/? (->> (m/ap (let [n (m/amb 24 79 67 34 18 9 99 37)] (m/? (m/sleep n n)))) (debounce 50) (m/reduce conj))) #_=> [24 79 9 37] ```
(?= flow)
Alias for (?> ##Inf flow)
Alias for `(?> ##Inf flow)`
(?> flow)
(?> par flow)
Forks current evaluation context by given flow. Evaluation resumes whenever the flow transfers, result is returned or
rethrown according to transfer status. Each transfer creates a new processing branch and defines a new evaluation
context inherited from its parent. par
is an optional positive number, defaulting to 1, defining the maximal count
of processing branches allowed to be run concurrently. Interrupting the parent evaluation context cancels the forking
flow and interrupts all processing branches currently being run and those subsequently run. The evaluation context is
undefined by default and can be defined with ap
.
Example :
(require '[missionary.core :as m])
(m/? (m/reduce conj (m/ap (inc (m/?> (m/seed [1 2 3]))))))
#_=> [2 3 4]
Example :
(require '[missionary.core :as m])
(m/? (->> (m/ap
(let [x (m/?> 5 (m/seed [19 57 28 6 87]))]
(m/? (m/sleep x x))))
(m/reduce conj)))
#_=> [6 19 28 57 87] ;; in 87 ms
Forks current evaluation context by given flow. Evaluation resumes whenever the flow transfers, result is returned or rethrown according to transfer status. Each transfer creates a new processing branch and defines a new evaluation context inherited from its parent. `par` is an optional positive number, defaulting to 1, defining the maximal count of processing branches allowed to be run concurrently. Interrupting the parent evaluation context cancels the forking flow and interrupts all processing branches currently being run and those subsequently run. The evaluation context is undefined by default and can be defined with `ap`. Example : ```clojure (require '[missionary.core :as m]) (m/? (m/reduce conj (m/ap (inc (m/?> (m/seed [1 2 3])))))) #_=> [2 3 4] ``` Example : ```clojure (require '[missionary.core :as m]) (m/? (->> (m/ap (let [x (m/?> 5 (m/seed [19 57 28 6 87]))] (m/? (m/sleep x x)))) (m/reduce conj))) #_=> [6 19 28 57 87] ;; in 87 ms ```
(absolve task)
Returns a task running given task
completing with a zero-argument function and completing with the result of this function call.
Returns a task running given `task` completing with a zero-argument function and completing with the result of this function call.
(amb)
(amb form)
(amb form & forms)
In an ap
block, evaluates each form sequentially and returns successive results.
In an `ap` block, evaluates each form sequentially and returns successive results.
(amb=)
(amb= form)
(amb= form & forms)
In an ap
block, evaluates each form concurrently and returns results in order of availability.
In an `ap` block, evaluates each form concurrently and returns results in order of availability.
(ap & body)
Returns a discrete flow evaluating body
(in an implicit do
) in a new evaluation context and producing values of each
subsequent fork. Body evaluation can be parked by a task with ?
and forked by a flow with ?>
and ?<
. Evaluation
and transfers are eager, backpressured by downstream transfers. Cancelling an ap
process interrupts its root
evaluation context.
Returns a discrete flow evaluating `body` (in an implicit `do`) in a new evaluation context and producing values of each subsequent fork. Body evaluation can be parked by a task with `?` and forked by a flow with `?>` and `?<`. Evaluation and transfers are eager, backpressured by downstream transfers. Cancelling an `ap` process interrupts its root evaluation context.
(attempt task)
Returns a task always succeeding with result of given task
wrapped in a zero-argument function returning result if successful or throwing exception if failed.
Returns a task always succeeding with result of given `task` wrapped in a zero-argument function returning result if successful or throwing exception if failed.
A java.util.concurrent.Executor
optimized for blocking evaluation.
A `java.util.concurrent.Executor` optimized for blocking evaluation.
(buffer c f)
Returns a discrete flow producing values emitted by given discrete flow
, accumulating upstream overflow up to capacity
items.
Returns a discrete flow producing values emitted by given discrete `flow`, accumulating upstream overflow up to `capacity` items.
(compel task)
Inhibits cancellation signal of given task
.
Inhibits cancellation signal of given `task`.
(cp & body)
Returns a continuous flow evaluating body
(in an implicit do
) in a new evaluation context and producing values of
each subsequent fork. Body evaluation can be forked by a continuous flow with ?<
. Evaluation and transfers are lazy,
driven by downstream sampling. Cancelling an cp
process interrupts its root evaluation context.
Returns a continuous flow evaluating `body` (in an implicit `do`) in a new evaluation context and producing values of each subsequent fork. Body evaluation can be forked by a continuous flow with `?<`. Evaluation and transfers are lazy, driven by downstream sampling. Cancelling an `cp` process interrupts its root evaluation context.
A java.util.concurrent.Executor
optimized for non-blocking evaluation.
A `java.util.concurrent.Executor` optimized for non-blocking evaluation.
(dfv)
Creates an instance of dataflow variable (aka single-assignment).
A dataflow variable is a function implementing assign
on 1-arity and deref
on 2-arity (as task). assign
immediately binds the variable to given value if not already bound and returns bound value. deref
is a task completing with the value bound to the variable as soon as it's available.
Cancelling a deref
task makes it fail immediately.
Creates an instance of dataflow variable (aka single-assignment). A dataflow variable is a function implementing `assign` on 1-arity and `deref` on 2-arity (as task). `assign` immediately binds the variable to given value if not already bound and returns bound value. `deref` is a task completing with the value bound to the variable as soon as it's available. Cancelling a `deref` task makes it fail immediately. ```
(eduction xf* flow)
Returns a discrete flow running given discrete flow
and transforming values with the composition of given transducers xf*
.
Cancelling propagates to upstream flow. Early termination by the transducing stage (via reduced
or throwing) cancels upstream flow.
Example :
(? (->> (seed (range 10))
(eduction (filter odd?) (mapcat range) (partition-all 4))
(reduce conj)))
#_=> [[0 0 1 2] [0 1 2 3] [4 0 1 2] [3 4 5 6] [0 1 2 3] [4 5 6 7] [8]]
Returns a discrete flow running given discrete `flow` and transforming values with the composition of given transducers `xf*`. Cancelling propagates to upstream flow. Early termination by the transducing stage (via `reduced` or throwing) cancels upstream flow. Example : ```clojure (? (->> (seed (range 10)) (eduction (filter odd?) (mapcat range) (partition-all 4)) (reduce conj))) #_=> [[0 0 1 2] [0 1 2 3] [4 0 1 2] [3 4 5 6] [0 1 2 3] [4 5 6 7] [8]] ```
(group-by kf f)
Returns a discrete flow running given discrete flow, calling given key function on each produced value, grouping values according to keys returned by the function, and producing a key-group pair for each grouping found. A group is a flow consuming values matching a key. Upstream values are dispatched in constant time to their group consumer.
Cancelling a group consumer makes it fail immediately. If a value is subsequently found for the same grouping, the key-group pair is produced again, including in the special case where the consumer is cancelled while a transfer was pending. Cancelling a group consumer has no effect when the main process is cancelled.
If upstream fails, or if the key function throws, then upstream is cancelled and flushed and the error is propagated downstream.
When the last upstream value is consumed, downstream terminates along with each active consumer and subsequent ones.
Concurrent consumers on a single group are not allowed, attempting to do so will fail the latest consumer.
Example :
(def words ["Air" "Bud" "Cup" "Awake" "Break" "Chunk" "Ant" "Big" "Check"])
(def groups
(m/ap (let [[k >x] (m/?= (m/group-by (juxt first count) (m/seed words)))]
[k (m/? (m/reduce conj >x))])))
(m/? (m/reduce conj {} groups))
#_=> {[\C 3] ["Cup"],
[\B 5] ["Break"],
[\A 5] ["Awake"],
[\B 3] ["Bud" "Big"],
[\A 3] ["Air" "Ant"],
[\C 5] ["Chunk" "Check"]}
Returns a discrete flow running given discrete flow, calling given key function on each produced value, grouping values according to keys returned by the function, and producing a key-group pair for each grouping found. A group is a flow consuming values matching a key. Upstream values are dispatched in constant time to their group consumer. Cancelling a group consumer makes it fail immediately. If a value is subsequently found for the same grouping, the key-group pair is produced again, including in the special case where the consumer is cancelled while a transfer was pending. Cancelling a group consumer has no effect when the main process is cancelled. If upstream fails, or if the key function throws, then upstream is cancelled and flushed and the error is propagated downstream. When the last upstream value is consumed, downstream terminates along with each active consumer and subsequent ones. Concurrent consumers on a single group are not allowed, attempting to do so will fail the latest consumer. Example : ```clojure (def words ["Air" "Bud" "Cup" "Awake" "Break" "Chunk" "Ant" "Big" "Check"]) (def groups (m/ap (let [[k >x] (m/?= (m/group-by (juxt first count) (m/seed words)))] [k (m/? (m/reduce conj >x))]))) (m/? (m/reduce conj {} groups)) #_=> {[\C 3] ["Cup"], [\B 5] ["Break"], [\A 5] ["Awake"], [\B 3] ["Bud" "Big"], [\A 3] ["Air" "Ant"], [\C 5] ["Chunk" "Check"]} ```
(holding lock & body)
acquire
s given semaphore
and evaluates body
(in an implicit do
), ensuring semaphore
is release
d after evaluation.
`acquire`s given `semaphore` and evaluates `body` (in an implicit `do`), ensuring `semaphore` is `release`d after evaluation.
(join c)
(join c & ts)
Returns a task running given tasks
concurrently.
If every task succeeds, join
completes with the result of applying f
to these results.
If any task fails, others are cancelled then join
fails with this error.
Cancelling propagates to children tasks.
Example :
(? (join vector (sleep 1000 1) (sleep 1000 2)))
#_=> [1 2] ;; 1 second later
Returns a task running given `tasks` concurrently. If every task succeeds, `join` completes with the result of applying `f` to these results. If any task fails, others are cancelled then `join` fails with this error. Cancelling propagates to children tasks. Example : ```clojure (? (join vector (sleep 1000 1) (sleep 1000 2))) #_=> [1 2] ;; 1 second later ```
(latest f & flows)
Returns a flow running an arbitrary number of flows concurrently. The process is ready to transfer when at least one input is ready to transfer. On transfer, all ready inputs are transferred, the function is called with the latest value of each input and the result is returned. If an input emits consecutive values, all of them are transferred and only the latest one is retained. Each input must be initially ready.
Input failures and exceptions thrown by f
cancel the process and propagate the error. The process terminates when all
inputs are terminated. Cancelling the process cancels all inputs.
(defn sleep-emit [delays]
(reductions {} 0
(ap (let [n (?> (seed delays))]
(? (sleep n n))))))
(defn delay-each [delay input]
(ap (? (sleep delay (?> input)))))
(? (->> (latest vector
(sleep-emit [24 79 67 34])
(sleep-emit [86 12 37 93]))
(delay-each 50)
(reduce conj)))
#_=> [[0 0] [24 0] [24 86] [79 12] [79 37] [67 37] [34 93]]
Returns a flow running an arbitrary number of flows concurrently. The process is ready to transfer when at least one input is ready to transfer. On transfer, all ready inputs are transferred, the function is called with the latest value of each input and the result is returned. If an input emits consecutive values, all of them are transferred and only the latest one is retained. Each input must be initially ready. Input failures and exceptions thrown by `f` cancel the process and propagate the error. The process terminates when all inputs are terminated. Cancelling the process cancels all inputs. ```clojure (defn sleep-emit [delays] (reductions {} 0 (ap (let [n (?> (seed delays))] (? (sleep n n)))))) (defn delay-each [delay input] (ap (? (sleep delay (?> input))))) (? (->> (latest vector (sleep-emit [24 79 67 34]) (sleep-emit [86 12 37 93])) (delay-each 50) (reduce conj))) #_=> [[0 0] [24 0] [24 86] [79 12] [79 37] [67 37] [34 93]] ```
(mbx)
Creates an instance of mailbox.
A mailbox is a function implementing post
on 1-arity and fetch
on 2-arity (as task). post
immediately pushes given value to mailbox and returns nil. fetch
is a task pulling a value from mailbox as soon as it's non-empty and completing with this value.
Cancelling a fetch
task makes it fail immediately.
Example : an actor is a mailbox associated with a process consuming messages.
(defn crash [^Throwable e] ;; let it crash philosophy
(.printStackTrace e)
(System/exit -1))
(defn actor
([init] (actor init crash))
([init fail]
(let [self (mbx)]
((sp
(loop [b init]
(recur (b self (? self)))))
nil fail)
self)))
(def counter
(actor
((fn beh [n]
(fn [self cust]
(cust n)
(beh (inc n)))) 0)))
(counter prn) ;; prints 0
(counter prn) ;; prints 1
(counter prn) ;; prints 2
Creates an instance of mailbox. A mailbox is a function implementing `post` on 1-arity and `fetch` on 2-arity (as task). `post` immediately pushes given value to mailbox and returns nil. `fetch` is a task pulling a value from mailbox as soon as it's non-empty and completing with this value. Cancelling a `fetch` task makes it fail immediately. Example : an actor is a mailbox associated with a process consuming messages. ```clojure (defn crash [^Throwable e] ;; let it crash philosophy (.printStackTrace e) (System/exit -1)) (defn actor ([init] (actor init crash)) ([init fail] (let [self (mbx)] ((sp (loop [b init] (recur (b self (? self))))) nil fail) self))) (def counter (actor ((fn beh [n] (fn [self cust] (cust n) (beh (inc n)))) 0))) (counter prn) ;; prints 0 (counter prn) ;; prints 1 (counter prn) ;; prints 2 ```
(memo t)
Returns a new publisher memoizing the result of task t
.
As long as the task process did not terminate spontaneously, running the publisher as a task registers a subscription. Cancelling a subscription deregisters it. A new task process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the task process terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately with the process result.
Example :
(require '[missionary.core :as m])
(def fib42
(m/memo
(m/via m/cpu
(println "Computing 42th fibonacci...")
((fn fib [n]
(case n
0 0
1 1
(+ (fib (dec n))
(fib (dec (dec n))))))
42))))
(fib42 prn prn) ;; expensive computation starts here, result is eventually printed
(fib42 prn prn) ;; expensive computation doesn't run again, previous result is reused
Returns a new publisher memoizing the result of task `t`. As long as the task process did not terminate spontaneously, running the publisher as a task registers a subscription. Cancelling a subscription deregisters it. A new task process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the task process terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately with the process result. Example : ```clojure (require '[missionary.core :as m]) (def fib42 (m/memo (m/via m/cpu (println "Computing 42th fibonacci...") ((fn fib [n] (case n 0 0 1 1 (+ (fib (dec n)) (fib (dec (dec n)))))) 42)))) (fib42 prn prn) ;; expensive computation starts here, result is eventually printed (fib42 prn prn) ;; expensive computation doesn't run again, previous result is reused ```
The empty flow. Doesn't produce any value and terminates immediately. Cancelling has no effect.
Example :
(? (reduce conj none))
#_=> []
The empty flow. Doesn't produce any value and terminates immediately. Cancelling has no effect. Example : ```clojure (? (reduce conj none)) #_=> [] ```
(observe s)
Returns a discrete flow observing values produced by a non-backpressured subject. subject
must be a function taking a
callback and returning a cleanup thunk. On initialization, the process calls the subject with a fresh callback. Passing
a value to the callback makes the process ready to transfer this value. Cancelling the process makes it fail immediately
with an instance of missionary.Cancelled
and terminates the process. The cleanup thunk is called on termination. The
callback throws an Error
if the process is cancelled or terminated, or if a transfer is pending.
Returns a discrete flow observing values produced by a non-backpressured subject. `subject` must be a function taking a callback and returning a cleanup thunk. On initialization, the process calls the subject with a fresh callback. Passing a value to the callback makes the process ready to transfer this value. Cancelling the process makes it fail immediately with an instance of `missionary.Cancelled` and terminates the process. The cleanup thunk is called on termination. The callback throws an `Error` if the process is cancelled or terminated, or if a transfer is pending.
(publisher f)
Returns a org.reactivestreams.Publisher
running given discrete flow
on each subscription.
Returns a `org.reactivestreams.Publisher` running given discrete `flow` on each subscription.
(race)
(race & ts)
Returns a task running given tasks
concurrently.
If any task succeeds, others are cancelled then race
completes with this result.
If every task fails, race
fails.
Cancelling propagates to children tasks.
Example :
(? (race (sleep 1000 1) (sleep 2000 2)))
#_=> 1 ;; 1 second later
Returns a task running given `tasks` concurrently. If any task succeeds, others are cancelled then `race` completes with this result. If every task fails, `race` fails. Cancelling propagates to children tasks. Example : ```clojure (? (race (sleep 1000 1) (sleep 2000 2))) #_=> 1 ;; 1 second later ```
(rdv)
Creates an instance of synchronous rendez-vous.
A synchronous rendez-vous is a function implementing give
on its 1-arity and take
on its 2-arity (as task). give
takes a value to be transferred and returns a task completing with nil as soon as a taker is available. take
is a task completing with transferred value as soon as a giver is available.
Cancelling give
and take
tasks makes them fail immediately.
Example : producer / consumer stream communication
(defn reducer [rf i take]
(sp
(loop [r i]
(let [x (? take)]
(if (identical? x take)
r (recur (rf r x)))))))
(defn iterator [give xs]
(sp
(loop [xs (seq xs)]
(if-some [[x & xs] xs]
(do (? (give x))
(recur xs))
(? (give give))))))
(def stream (rdv))
(? (join {} (iterator stream (range 100)) (reducer + 0 stream))) ;; returns 4950
Creates an instance of synchronous rendez-vous. A synchronous rendez-vous is a function implementing `give` on its 1-arity and `take` on its 2-arity (as task). `give` takes a value to be transferred and returns a task completing with nil as soon as a taker is available. `take` is a task completing with transferred value as soon as a giver is available. Cancelling `give` and `take` tasks makes them fail immediately. Example : producer / consumer stream communication ```clojure (defn reducer [rf i take] (sp (loop [r i] (let [x (? take)] (if (identical? x take) r (recur (rf r x))))))) (defn iterator [give xs] (sp (loop [xs (seq xs)] (if-some [[x & xs] xs] (do (? (give x)) (recur xs)) (? (give give)))))) (def stream (rdv)) (? (join {} (iterator stream (range 100)) (reducer + 0 stream))) ;; returns 4950 ```
(reactor & body)
Use lazy publishers instead - memo, stream, signal.
Use lazy publishers instead - memo, stream, signal.
(reactor-call boot)
Use lazy publishers instead - memo, stream, signal.
Use lazy publishers instead - memo, stream, signal.
(reduce rf flow)
(reduce rf i flow)
Returns a task reducing values produced by given discrete flow
with rf
, starting with init
(or, if not provided, the result of calling rf
with no argument).
Cancelling propagates to upstream flow. Early termination by rf
(via reduced
or throwing) cancels upstream flow.
Example :
(? (reduce + (seed (range 10))))
#_=> 45
Returns a task reducing values produced by given discrete `flow` with `rf`, starting with `init` (or, if not provided, the result of calling `rf` with no argument). Cancelling propagates to upstream flow. Early termination by `rf` (via `reduced` or throwing) cancels upstream flow. Example : ```clojure (? (reduce + (seed (range 10)))) #_=> 45 ```
(reductions rf f)
(reductions rf i f)
Returns a discrete flow running given discrete flow
and emitting given init
value (or, if not provided, the result of calling rf
with no argument) followed by successive reductions (by rf) of upstream values with previously emitted value.
Cancelling propagates to upstream flow. Early termination by rf
(via reduced
or throwing) cancels upstream flow.
Example :
(? (->> [1 2 3 4 5]
(seed)
(reductions +)
(reduce conj)))
#_=> [0 1 3 6 10 15]
Returns a discrete flow running given discrete `flow` and emitting given `init` value (or, if not provided, the result of calling `rf` with no argument) followed by successive reductions (by rf) of upstream values with previously emitted value. Cancelling propagates to upstream flow. Early termination by `rf` (via `reduced` or throwing) cancels upstream flow. Example : ```clojure (? (->> [1 2 3 4 5] (seed) (reductions +) (reduce conj))) #_=> [0 1 3 6 10 15] ```
(relieve flow)
(relieve sg flow)
Returns a flow consuming input flow
as fast as possible and producing aggregates of successive values according to
downstream transfer rate. The set of transferred values must form a semigroup with given function sg
as the internal
binary operation, i.e. sg
must be associative. If sg
is not provided, {}
is used by default, i.e. all values but
the latest are discarded.
Cancelling propagates to upstream. If sg
throws, upstream flow
is cancelled.
Example :
;; Delays each `input` value by `delay` milliseconds
(defn delay-each [delay input]
(ap (? (sleep delay (?> input)))))
(? (->> (ap (let [n (?> (seed [24 79 67 34 18 9 99 37]))]
(? (sleep n n))))
(relieve +)
(delay-each 80)
(reduce conj)))
#_=> [24 79 67 61 99 37]
Returns a flow consuming input `flow` as fast as possible and producing aggregates of successive values according to downstream transfer rate. The set of transferred values must form a semigroup with given function `sg` as the internal binary operation, i.e. `sg` must be associative. If `sg` is not provided, `{}` is used by default, i.e. all values but the latest are discarded. Cancelling propagates to upstream. If `sg` throws, upstream `flow` is cancelled. Example : ```clojure ;; Delays each `input` value by `delay` milliseconds (defn delay-each [delay input] (ap (? (sleep delay (?> input))))) (? (->> (ap (let [n (?> (seed [24 79 67 34 18 9 99 37]))] (? (sleep n n)))) (relieve +) (delay-each 80) (reduce conj))) #_=> [24 79 67 61 99 37] ```
(sample f sampled* sampler)
Returns a flow running an arbitrary number of sampled flows concurrently with a sampler flow. The process is ready to transfer when the sampler is ready to transfer. On transfer, all ready inputs are transferred, the function is called with the latest value of each input and the result is returned. If a sampled input emits consecutive values, all of them are transferred and only the latest one is retained. Each sampled input must be initially ready.
When the sampler input terminates, all sampled inputs are cancelled. Input failures and exceptions thrown by f
cancel
the process, and propagate the error. The process terminates when all input flows are terminated. Cancelling the process
cancels the sampler input.
Example :
(defn sleep-emit [delays]
(ap (let [n (?> (seed delays))]
(? (sleep n n)))))
(defn delay-each [delay input]
(ap (? (sleep delay (?> input)))))
(m/? (->> (m/sample vector
(m/reductions {} 0 (sleep-emit [24 79 67 34]))
(sleep-emit [86 12 37 93]))
(delay-each 50)
(m/reduce conj)))
#_=> [[24 86] [24 12] [79 37] [67 93]]
Returns a flow running an arbitrary number of sampled flows concurrently with a sampler flow. The process is ready to transfer when the sampler is ready to transfer. On transfer, all ready inputs are transferred, the function is called with the latest value of each input and the result is returned. If a sampled input emits consecutive values, all of them are transferred and only the latest one is retained. Each sampled input must be initially ready. When the sampler input terminates, all sampled inputs are cancelled. Input failures and exceptions thrown by `f` cancel the process, and propagate the error. The process terminates when all input flows are terminated. Cancelling the process cancels the sampler input. Example : ```clojure (defn sleep-emit [delays] (ap (let [n (?> (seed delays))] (? (sleep n n))))) (defn delay-each [delay input] (ap (? (sleep delay (?> input))))) (m/? (->> (m/sample vector (m/reductions {} 0 (sleep-emit [24 79 67 34])) (sleep-emit [86 12 37 93])) (delay-each 50) (m/reduce conj))) #_=> [[24 86] [24 12] [79 37] [67 93]] ```
(seed coll)
Returns a discrete flow producing values from given collection
. Cancelling before having reached the end makes the flow fail immediately.
Returns a discrete flow producing values from given `collection`. Cancelling before having reached the end makes the flow fail immediately.
(sem)
(sem n)
Creates a semaphore initialized with n tokens (1 if not provided, aka mutex).
A semaphore is a function implementing release
on 0-arity and acquire
on 2-arity (as task). release
immediately makes a token available and returns nil. acquire
is a task completing with nil as soon as a token is available.
Cancelling an acquire
task makes it fail immediately.
Example : dining philosophers
(defn phil [name f1 f2]
(sp
(while true
(prn name :thinking)
(? (sleep 500))
(holding f1
(holding f2
(prn name :eating)
(? (sleep 600)))))))
(def forks (vec (repeatedly 5 sem)))
(? (timeout 10000
(join vector
(phil "descartes" (forks 0) (forks 1))
(phil "hume" (forks 1) (forks 2))
(phil "plato" (forks 2) (forks 3))
(phil "nietzsche" (forks 3) (forks 4))
(phil "kant" (forks 0) (forks 4)))))
Creates a semaphore initialized with n tokens (1 if not provided, aka mutex). A semaphore is a function implementing `release` on 0-arity and `acquire` on 2-arity (as task). `release` immediately makes a token available and returns nil. `acquire` is a task completing with nil as soon as a token is available. Cancelling an `acquire` task makes it fail immediately. Example : dining philosophers ```clojure (defn phil [name f1 f2] (sp (while true (prn name :thinking) (? (sleep 500)) (holding f1 (holding f2 (prn name :eating) (? (sleep 600))))))) (def forks (vec (repeatedly 5 sem))) (? (timeout 10000 (join vector (phil "descartes" (forks 0) (forks 1)) (phil "hume" (forks 1) (forks 2)) (phil "plato" (forks 2) (forks 3)) (phil "nietzsche" (forks 3) (forks 4)) (phil "kant" (forks 0) (forks 4))))) ```
(signal flow)
(signal sg flow)
Returns a new publisher exposing successive values of flow
regardless of subscribers' sampling rate. The set of
transferred values must form a semigroup with given function sg
as the internal binary operation, i.e. sg
must be
associative. If sg
is not provided, {}
is used by default, i.e. all values but the latest are discarded.
As long as the flow process did not terminate spontaneously, running the publisher as a flow registers a subscription. Cancelling a subscription deregisters it. A new flow process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the flow process has terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately after consuming the latest item.
Example :
(require '[missionary.core :as m])
(def !input (atom 1))
(def main ; this is a reactive computation, the println reacts to input changes
(let [<x (m/signal (m/watch !input)) ; continuous signal reflecting atom state
<y (m/signal (m/latest + <x <x))] ; derived computation, diamond shape
(m/reduce (fn [_ x] (prn x)) nil <y))) ; discrete effect performed on successive values
(def dispose!
(main
#(prn ::success %)
#(prn ::crash %))) ; prints 2
(swap! !input inc) ; prints 4
; Each change on the input propagates atomically through the graph.
; 3 is an inconsistent state and is therefore not computed.
(dispose!) ; cleanup, deregisters the atom watch
Returns a new publisher exposing successive values of `flow` regardless of subscribers' sampling rate. The set of transferred values must form a semigroup with given function `sg` as the internal binary operation, i.e. `sg` must be associative. If `sg` is not provided, `{}` is used by default, i.e. all values but the latest are discarded. As long as the flow process did not terminate spontaneously, running the publisher as a flow registers a subscription. Cancelling a subscription deregisters it. A new flow process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the flow process has terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately after consuming the latest item. Example : ```clojure (require '[missionary.core :as m]) (def !input (atom 1)) (def main ; this is a reactive computation, the println reacts to input changes (let [<x (m/signal (m/watch !input)) ; continuous signal reflecting atom state <y (m/signal (m/latest + <x <x))] ; derived computation, diamond shape (m/reduce (fn [_ x] (prn x)) nil <y))) ; discrete effect performed on successive values (def dispose! (main #(prn ::success %) #(prn ::crash %))) ; prints 2 (swap! !input inc) ; prints 4 ; Each change on the input propagates atomically through the graph. ; 3 is an inconsistent state and is therefore not computed. (dispose!) ; cleanup, deregisters the atom watch ```
(sleep d)
(sleep d x)
Returns a task completing with given value (nil if not provided) after given duration (in milliseconds).
Cancelling a sleep task makes it fail immediately.
Example :
(? (sleep 1000 42))
#_=> 42 ;; 1 second later
Returns a task completing with given value (nil if not provided) after given duration (in milliseconds). Cancelling a sleep task makes it fail immediately. Example : ```clojure (? (sleep 1000 42)) #_=> 42 ;; 1 second later ```
(sp & body)
Returns a task evaluating body
(in an implicit do
) in a new evaluation context and completing its result. Body
evaluation can be parked by a task with ?
. Cancelling a sp
process interrupts its evaluation context.
Returns a task evaluating `body` (in an implicit `do`) in a new evaluation context and completing its result. Body evaluation can be parked by a task with `?`. Cancelling a `sp` process interrupts its evaluation context.
(stream f)
Returns a new publisher distributing successive items emitted by flow f
while collecting subscribers' backpressure.
As long as the flow process did not terminate spontaneously, running the publisher as a flow registers a subscription. Cancelling a subscription deregisters it. A new flow process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the flow process has terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately after consuming the current item, if any.
Example :
(require '[missionary.core :as m])
(def >clock ;; A shared process emitting `nil` every second.
(m/stream
(m/ap
(loop [i 0]
(m/amb
(m/? (m/sleep 1000))
(recur (inc i)))))))
(defn counter [r _] (inc r)) ;; A reducing function counting the number of items.
((m/join vector
(m/reduce counter 0 (m/eduction (take 3) >clock))
(m/reduce counter 0 (m/eduction (take 4) >clock)))
prn prn) ;; After 4 seconds, prints [3 4]
Returns a new publisher distributing successive items emitted by flow `f` while collecting subscribers' backpressure. As long as the flow process did not terminate spontaneously, running the publisher as a flow registers a subscription. Cancelling a subscription deregisters it. A new flow process is spawned when the first subscription is registered and cancelled when the last subscription is deregistered. After the flow process has terminated spontaneously, every registered subscription and any subsequent subscription terminates immediately after consuming the current item, if any. Example : ```clojure (require '[missionary.core :as m]) (def >clock ;; A shared process emitting `nil` every second. (m/stream (m/ap (loop [i 0] (m/amb (m/? (m/sleep 1000)) (recur (inc i))))))) (defn counter [r _] (inc r)) ;; A reducing function counting the number of items. ((m/join vector (m/reduce counter 0 (m/eduction (take 3) >clock)) (m/reduce counter 0 (m/eduction (take 4) >clock))) prn prn) ;; After 4 seconds, prints [3 4] ```
(subscribe pub)
Returns a discrete flow subscribing to given org.reactivestreams.Publisher
.
Returns a discrete flow subscribing to given `org.reactivestreams.Publisher`.
(timeout task delay)
(timeout task delay value)
Returns a task running given task
and completing with its result if available within specified delay
(in
milliseconds). Otherwise, input is cancelled and the process succeeds with value
, or nil
if not provided.
(m/? (m/timeout (m/sleep 20 :a) 25 :b)) ;; :a after 20ms
(m/? (m/timeout (m/sleep 20 :a) 15 :b)) ;; :b after 15ms
(m/? (m/timeout (m/sleep 20 :a) 15)) ;; nil after 15ms
Returns a task running given `task` and completing with its result if available within specified `delay` (in milliseconds). Otherwise, input is cancelled and the process succeeds with `value`, or `nil` if not provided. ```clojure (m/? (m/timeout (m/sleep 20 :a) 25 :b)) ;; :a after 20ms (m/? (m/timeout (m/sleep 20 :a) 15 :b)) ;; :b after 15ms (m/? (m/timeout (m/sleep 20 :a) 15)) ;; nil after 15ms ```
(via exec & body)
Returns a task evaluating body (in an implicit do
) on given java.util.concurrent.Executor
and completing with its result.
Cancellation interrupts the evaluating thread.
Not supported on clojurescript.
Example :
Returns a task evaluating body (in an implicit `do`) on given `java.util.concurrent.Executor` and completing with its result. Cancellation interrupts the evaluating thread. Not supported on clojurescript. Example : ```clojure ```
(via-call e t)
Same as via
, except the expression to evaluate is provided as a zero-arity function on second argument.
Not supported on clojurescript.
(? (via-call blk read-line))
;; reads a line from stdin and returns it
Same as `via`, except the expression to evaluate is provided as a zero-arity function on second argument. Not supported on clojurescript. ```clojure (? (via-call blk read-line)) ;; reads a line from stdin and returns it ```
(watch r)
Returns a continuous flow reflecting the current state of a reference type. reference
must support add-watch
,
remove-watch
and deref
. On initialization, the process is ready to transfer. On transfer, the current state is
returned. Whenever the state of the reference changes and a transfer is not pending, the process becomes ready to
transfer again. Cancelling the process makes it fail immediately with an instance of missionary.Cancelled
and
terminates the process.
Returns a continuous flow reflecting the current state of a reference type. `reference` must support `add-watch`, `remove-watch` and `deref`. On initialization, the process is ready to transfer. On transfer, the current state is returned. Whenever the state of the reference changes and a transfer is not pending, the process becomes ready to transfer again. Cancelling the process makes it fail immediately with an instance of `missionary.Cancelled` and terminates the process.
(zip c f & fs)
Returns a discrete flow running given discrete flows
concurrently and emitting the result of applying f
to the set of first values emitted by each upstream flow, followed by the result of applying f
to the set of second values and so on, until any upstream flow terminates, at which point the flow will cancel all other upstream flows and wait for their termination.
Cancelling propagates to every upstream flow. If any upstream flow fails or if f
throws, the flow is cancelled.
Example :
(m/? (->> (m/zip vector
(m/seed [1 2 3])
(m/seed [:a :b :c]))
(m/reduce conj)))
#_=> [[1 :a] [2 :b] [3 :c]]
Returns a discrete flow running given discrete `flows` concurrently and emitting the result of applying `f` to the set of first values emitted by each upstream flow, followed by the result of applying `f` to the set of second values and so on, until any upstream flow terminates, at which point the flow will cancel all other upstream flows and wait for their termination. Cancelling propagates to every upstream flow. If any upstream flow fails or if `f` throws, the flow is cancelled. Example : ```clojure (m/? (->> (m/zip vector (m/seed [1 2 3]) (m/seed [:a :b :c])) (m/reduce conj))) #_=> [[1 :a] [2 :b] [3 :c]] ```
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close