#once #shareable #async #value #container #set #watch

async-once-watch

Asynchronous and shareable container which value is set once

1 unstable release

0.1.1 Feb 20, 2022
0.1.0 Feb 20, 2022

#1059 in Concurrency

MIT license

6KB
71 lines

async-watch-once

[ crates.io | docs.rs ]

This crate provides a shareable container OnceWatch<T> in Rust, which value is set once. The readers wait in asynchronous manner until the value is ready.

use async_once_watch::OnceWatch;
use async_std::task::{sleep, spawn};
use once_cell::sync::Lazy;
use std::time::Duration;

static STATE: Lazy<OnceWatch<u8>> = Lazy::new(OnceWatch::new);
let secret = 10;

/* Writer */
spawn(async move {
    sleep(Duration::from_millis(500)).await;

    // First write is fine
    let ok = STATE.set(secret).is_ok();
    assert!(ok);

    // Second write is not allowed
    let ok = STATE.set(secret).is_ok();
    assert!(!ok);
});

/* Reader */
spawn(async move {
    let received = *STATE.get().await;
    assert_eq!(received, secret);
});

License

MIT license. See license file.


lib.rs:

Asynchronous and shareable container which value is set once.

The OnceWatch is a container with get() and set() methods. The values is set at most once. The readers call get() and wait until the value is ready.

use async_once_watch::OnceWatch;
use async_std::task::{sleep, spawn};
use once_cell::sync::Lazy;
use std::time::Duration;

static STATE: Lazy<OnceWatch<u8>> = Lazy::new(OnceWatch::new);
let secret = 10;

/* Writer */
spawn(async move {
    sleep(Duration::from_millis(500)).await;

    // First write is fine
    let ok = STATE.set(secret).is_ok();
    assert!(ok);

    // Second write is not allowed
    let ok = STATE.set(secret).is_ok();
    assert!(!ok);
});

/* Reader */
spawn(async move {
    let received = *STATE.get().await;
    assert_eq!(received, secret);
});

Dependencies

~2–7.5MB
~47K SLoC