Skip to content

Instantly share code, notes, and snippets.

@duanebester
Created February 25, 2025 17:11
Show Gist options
  • Save duanebester/c8a4e72a3eb1395e1ca90e084667fce1 to your computer and use it in GitHub Desktop.
Save duanebester/c8a4e72a3eb1395e1ca90e084667fce1 to your computer and use it in GitHub Desktop.
GPUI Async with Observe
// async-channel = "2.3.1"
// async-io = "2.4.0"
// gpui = { git = "https://github.com/zed-industries/zed" }
// rand = "0.9"
use async_channel::unbounded;
use async_io::Timer;
use gpui::{prelude::*, App, Application, Entity};
use rand::Rng;
use std::time::Duration;
struct Counter {
count: usize,
}
struct Change {
increment: usize,
}
fn main() {
Application::new().run(|cx: &mut App| {
let (tx, rx) = unbounded::<Change>();
let counter: Entity<Counter> = cx.new(|_cx| Counter { count: 0 });
// Simulate websocket server in background thread
cx.background_executor()
.spawn(async move {
loop {
let num = rand::rng().random_range(0..100);
tx.send(Change { increment: num }).await.unwrap();
Timer::after(Duration::from_secs(1)).await;
}
})
.detach();
// Spawn task to handle incoming changes
let clone = counter.clone();
cx.spawn(|mut cx| async move {
loop {
let change = rx.recv().await.unwrap();
println!("Incoming increment: {}", change.increment);
let _ = clone.update(&mut cx, |entity, cx| {
if entity.count > 1_000 {
println!("Resetting counter");
entity.count = 0;
}
entity.count += change.increment;
cx.notify();
});
}
})
.detach();
// Observe counter changes
cx.observe(&counter.clone(), |entity, cx| {
println!("Current count: {}", entity.read(cx).count);
})
.detach();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment