ownership_post.rs

 1use gpui::{App, Context, Entity, EventEmitter, prelude::*};
 2use gpui_platform::application;
 3
 4struct Counter {
 5    count: usize,
 6}
 7
 8struct Change {
 9    increment: usize,
10}
11
12impl EventEmitter<Change> for Counter {}
13
14fn main() {
15    application().run(|cx: &mut App| {
16        let counter: Entity<Counter> = cx.new(|_cx| Counter { count: 0 });
17        let subscriber = cx.new(|cx: &mut Context<Counter>| {
18            cx.subscribe(&counter, |subscriber, _emitter, event, _cx| {
19                subscriber.count += event.increment * 2;
20            })
21            .detach();
22
23            Counter {
24                count: counter.read(cx).count * 2,
25            }
26        });
27
28        counter.update(cx, |counter, cx| {
29            counter.count += 2;
30            cx.notify();
31            cx.emit(Change { increment: 2 });
32        });
33
34        assert_eq!(subscriber.read(cx).count, 4);
35    });
36}