How to create async HashMap singleton

I wanna create a async HashMap singleton, So any where can use it in my project.
The pseudo code:

static_or_lazy MY_SINGLETON Arc_or_noArc<tokio::sync::RwLock<HashMap<String, String>>> = ?
#tokio_main
fn main() {
    tokio::spawn(async move {
            how_to_get_MY_SINGLETON_item.await;  //?
        });
    tokio::spawn(async move {
            how_to_store_MY_SINGLETON_item.await;  //?
        });
}
#![feature(once_cell)]

use std::lazy::SyncLazy;
use std::collections::HashMap;
use tokio::sync::RwLock;

static MY_SINGLETON: SyncLazy<RwLock<HashMap<String, String>>> = SyncLazy::new(|| {
    RwLock::default()
});

#[tokio::main]
async fn main() {
    tokio::spawn(async move {
        MY_SINGLETON.read().await;  //?
    });
}

the #![feature(once_cell)] is a feature gate to make stdlib depends on the once_cell crate. You can use the once_cell::sync::Lazy with the stable toolchain.

2 Likes

Please link the other places you ask the question when you ask it multiple places.

I answered this question here. As I also said there, you should probably not be using the Tokio RwLock for this purpose.