Crates.io | async-once-watch |
lib.rs | async-once-watch |
version | 0.1.1 |
source | src |
created_at | 2022-02-20 09:15:00.063711 |
updated_at | 2022-02-20 11:33:01.466343 |
description | Asynchronous and shareable container which value is set once. |
homepage | https://github.com/jerry73204/async-once-watch |
repository | https://github.com/jerry73204/async-once-watch.git |
max_upload_size | |
id | 535642 |
size | 8,160 |
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);
});
MIT license. See license file.