zed/crates/gpui/examples/ownership_post.rs

36 lines
893 B
Rust
Raw Normal View History

2024-01-18 04:18:17 +00:00
use gpui::{prelude::*, App, AppContext, EventEmitter, Model, ModelContext};
struct Counter {
count: usize,
}
2024-01-18 14:01:46 +00:00
struct Change {
increment: usize,
}
impl EventEmitter<Change> for Counter {}
2024-01-18 04:18:17 +00:00
fn main() {
App::new().run(|cx: &mut AppContext| {
let counter: Model<Counter> = cx.new_model(|_cx| Counter { count: 0 });
2024-01-18 14:01:46 +00:00
let subscriber = cx.new_model(|cx: &mut ModelContext<Counter>| {
cx.subscribe(&counter, |subscriber, _emitter, event, _cx| {
subscriber.count += event.increment * 2;
2024-01-18 04:18:17 +00:00
})
.detach();
Counter {
count: counter.read(cx).count * 2,
}
});
counter.update(cx, |counter, cx| {
2024-01-18 14:01:46 +00:00
counter.count += 2;
2024-01-18 04:18:17 +00:00
cx.notify();
2024-01-18 14:01:46 +00:00
cx.emit(Change { increment: 2 });
2024-01-18 04:18:17 +00:00
});
2024-01-18 14:01:46 +00:00
assert_eq!(subscriber.read(cx).count, 4);
2024-01-18 04:18:17 +00:00
});
}