Usage
The channel
function creates a pair of Sender
and Receiver
. To create the channel provide its initial value.
Each receiver independently tracks the last observed value. To read the current value, use the receiver's observe
method. To wait for a change, call the async changed
method on the receiver. If the value implements Clone
, you can also use the recv
method to wait for a change and immediately read the new value.
To update the value, call the sender's send
method. This method is non-async and does not block the current thread - the value is updated immediately. This makes it convenient to send values from both async and synchronous contexts.
Examples
This example prints numbers from 0 to 9:
use ;
let = channel;
// Perform computations in another thread
spawn;
// Print the initial value (0)
let n = rx.observe;
println!;
block_on;
In this example a new thread is spawned, but you can also use the channel to update values from a future/async task.
Note that this channel does not have a message queue - it only stores the
latest update. Therefore, it does not guarantee that you will observe
every intermediate value. If you need to observe each change, use a
message-queue channel such as async-channel
.