basic_actor/
basic_actor.rs1use actor12::prelude::*;
2use actor12::{spawn, Envelope, MpscChannel, Init, Exec};
3use std::future::Future;
4
5pub struct Counter {
7 count: i32,
8}
9
10#[derive(Debug)]
12pub struct Increment;
13
14#[derive(Debug)]
15pub struct GetCount;
16
17impl Actor for Counter {
19 type Spec = i32; type Message = Envelope<(), anyhow::Result<()>>; type Channel = MpscChannel<Self::Message>;
22 type Cancel = ();
23 type State = ();
24
25 fn state(_spec: &Self::Spec) -> Self::State {}
26
27 fn init(ctx: Init<'_, Self>) -> impl Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
28 let initial_count = ctx.spec;
29 async move {
30 println!("Counter actor initialized with count: {}", initial_count);
31 Ok(Counter { count: initial_count })
32 }
33 }
34
35 async fn handle(&mut self, _ctx: Exec<'_, Self>, msg: Self::Message) {
36 self.count += 1;
37 println!("Count incremented to: {}", self.count);
38 let _ = msg.reply.send(Ok(()));
39 }
40}
41
42pub struct CounterReader {
44 counter_value: i32,
45}
46
47impl Actor for CounterReader {
48 type Spec = i32;
49 type Message = Envelope<(), anyhow::Result<i32>>;
50 type Channel = MpscChannel<Self::Message>;
51 type Cancel = ();
52 type State = ();
53
54 fn state(_spec: &Self::Spec) -> Self::State {}
55
56 fn init(ctx: Init<'_, Self>) -> impl Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
57 let initial_count = ctx.spec;
58 async move {
59 Ok(CounterReader { counter_value: initial_count })
60 }
61 }
62
63 async fn handle(&mut self, _ctx: Exec<'_, Self>, msg: Self::Message) {
64 println!("Current count requested: {}", self.counter_value);
65 let _ = msg.reply.send(Ok(self.counter_value));
66 }
67}
68
69#[tokio::main]
70async fn main() -> anyhow::Result<()> {
71 let counter = spawn::<Counter>(0);
73
74 counter.send(()).await?;
76 counter.send(()).await?;
77 counter.send(()).await?;
78
79 println!("Sent 3 increment messages");
80
81 Ok(())
86}