1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
use futures::channel::mpsc; use futures::channel::oneshot; #[allow(unused_imports)] use futures::stream::StreamExt; #[allow(unused_imports)] use std::future::Future; pub struct AsyncOnce<T> { sender: mpsc::UnboundedSender<oneshot::Sender<T>>, } impl<T: 'static + Clone> AsyncOnce<T> { #[cfg(all( feature = "tokio", not(feature = "async-std"), not(feature = "wasm-bindgen-futures") ))] pub fn new<F>(fut: F) -> AsyncOnce<T> where F: Future<Output = T> + Send + 'static, T: Send, { let (tx, mut rx) = mpsc::unbounded::<oneshot::Sender<T>>(); tokio::spawn(async move { let val = fut.await; while let Some(val_tx) = rx.next().await { let _ = val_tx.send(val.clone()); } }); AsyncOnce { sender: tx } } #[cfg(all( feature = "async-std", not(feature = "tokio"), not(feature = "wasm-bindgen-futures") ))] pub fn new<F>(fut: F) -> AsyncOnce<T> where F: Future<Output = T> + Send + 'static, T: Send, { let (tx, mut rx) = mpsc::unbounded::<oneshot::Sender<T>>(); async_std::task::spawn(async move { let val = fut.await; while let Some(val_tx) = rx.next().await { let _ = val_tx.send(val.clone()); } }); AsyncOnce { sender: tx } } #[cfg(all( feature = "wasm-bindgen-futures", not(feature = "tokio"), not(feature = "async-std") ))] pub fn new<F>(fut: F) -> AsyncOnce<T> where F: Future<Output = T> + 'static, { let (tx, mut rx) = mpsc::unbounded::<oneshot::Sender<T>>(); wasm_bindgen_futures::spawn_local(async move { let val = fut.await; while let Some(val_tx) = rx.next().await { let _ = val_tx.send(val.clone()); } }); AsyncOnce { sender: tx } } pub async fn get(&self) -> T { let (tx, rx) = oneshot::channel(); self.sender.unbounded_send(tx).unwrap(); rx.await.unwrap() } } #[cfg(all( feature = "tokio", not(feature = "async-std"), not(feature = "wasm-bindgen-futures") ))] #[test] fn lazy_static_test_for_tokio() { use lazy_static::lazy_static; use tokio::runtime::Runtime; lazy_static! { static ref FOO: AsyncOnce<u32> = AsyncOnce::new(async { 1 }); } let mut rt = Runtime::new().unwrap(); rt.block_on(async { assert_eq!(FOO.get().await, 1) }) } #[cfg(all( feature = "async-std", not(feature = "tokio"), not(feature = "wasm-bindgen-futures") ))] #[test] fn lazy_static_test_for_async_std() { use async_std::task; use lazy_static::lazy_static; lazy_static! { static ref FOO: AsyncOnce<u32> = AsyncOnce::new(async { 1 }); } task::block_on(async { assert_eq!(FOO.get().await, 1) }) }