Update kameo-actors example
This commit is contained in:
parent
0438032f18
commit
7b4a79c803
@ -1,34 +1,83 @@
|
||||
use std::error::Error;
|
||||
|
||||
use kameo::message::{Context, Message};
|
||||
use kameo::request::MessageSend;
|
||||
use kameo::{spawn, Actor};
|
||||
use kameo::message::{Message, Context};
|
||||
|
||||
#[derive(Actor)]
|
||||
pub struct HelloWorldActor;
|
||||
#[derive(Default, Actor)]
|
||||
pub struct CalculActor {
|
||||
value: i32,
|
||||
}
|
||||
|
||||
pub struct Greet(String);
|
||||
pub struct Reset(i32);
|
||||
pub struct Add(i32);
|
||||
pub struct Sub(i32);
|
||||
pub struct Mul(i32);
|
||||
pub struct Div(i32);
|
||||
pub struct Get;
|
||||
|
||||
impl Message<Greet> for HelloWorldActor {
|
||||
impl Message<Reset> for CalculActor {
|
||||
type Reply = ();
|
||||
|
||||
async fn handle(
|
||||
&mut self,
|
||||
Greet(greeting): Greet,
|
||||
_: Context<'_, Self, Self::Reply>,
|
||||
) -> Self::Reply {
|
||||
println!("{greeting}");
|
||||
&mut self,
|
||||
Reset(value): Reset,
|
||||
_: Context<'_, Self, Self::Reply>,
|
||||
) -> Self::Reply {
|
||||
self.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
impl Message<Add> for CalculActor {
|
||||
type Reply = ();
|
||||
|
||||
async fn handle(&mut self, Add(value): Add, _: Context<'_, Self, Self::Reply>) -> Self::Reply {
|
||||
self.value += value;
|
||||
}
|
||||
}
|
||||
|
||||
impl Message<Sub> for CalculActor {
|
||||
type Reply = ();
|
||||
|
||||
async fn handle(&mut self, Sub(value): Sub, _: Context<'_, Self, Self::Reply>) -> Self::Reply {
|
||||
self.value -= value;
|
||||
}
|
||||
}
|
||||
|
||||
impl Message<Mul> for CalculActor {
|
||||
type Reply = ();
|
||||
|
||||
async fn handle(&mut self, Mul(value): Mul, _: Context<'_, Self, Self::Reply>) -> Self::Reply {
|
||||
self.value *= value;
|
||||
}
|
||||
}
|
||||
|
||||
impl Message<Div> for CalculActor {
|
||||
type Reply = ();
|
||||
|
||||
async fn handle(&mut self, Div(value): Div, _: Context<'_, Self, Self::Reply>) -> Self::Reply {
|
||||
self.value /= value;
|
||||
}
|
||||
}
|
||||
|
||||
impl Message<Get> for CalculActor {
|
||||
type Reply = i32;
|
||||
|
||||
async fn handle(&mut self, _: Get, _: Context<'_, Self, Self::Reply>) -> Self::Reply {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let actor_ref = spawn(HelloWorldActor);
|
||||
let actor_ref = spawn(CalculActor::default());
|
||||
|
||||
actor_ref
|
||||
.tell(Greet("Hello world".to_string()))
|
||||
.send()
|
||||
.await?;
|
||||
actor_ref.tell(Add(5)).send().await?;
|
||||
actor_ref.tell(Mul(5)).send().await?;
|
||||
actor_ref.tell(Sub(3)).send().await?;
|
||||
let result = actor_ref.ask(Get).send().await?;
|
||||
|
||||
println!("Result is {result}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user