Skip to content

Instantly share code, notes, and snippets.

@justanotherdot
Created March 13, 2021 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justanotherdot/5eddc2771adc638878ebd9649ec030d5 to your computer and use it in GitHub Desktop.
Save justanotherdot/5eddc2771adc638878ebd9649ec030d5 to your computer and use it in GitHub Desktop.
use tokio;
use tokio::{task, task_local};
use std::cell::RefCell;
use std::collections::HashMap;
#[tokio::main]
async fn main() {
let handler = task::spawn(async {
task_local! {
pub static WRITER: RefCell<HashMap<String, i64>>;
}
let request_handler = || {
WRITER.with(|writer| {
*writer.borrow_mut().entry("value".to_string()).or_default() += 3;
writer.take().get("value").cloned()
})
};
WRITER.scope(RefCell::new(HashMap::new()), async move {
WRITER.with(|writer| {
writer.borrow_mut().insert("value".to_string(), 7);
});
WRITER.with(|writer| {
let v = writer.borrow().get("value").cloned();
assert_eq!(v, Some(7));
});
request_handler()
}).await
});
let result = handler.await.expect("urk");
assert_eq!(result, Some(10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment