diff --git a/kameo-actors/src/main.rs b/kameo-actors/src/main.rs index 671aeee..4c19e3e 100644 --- a/kameo-actors/src/main.rs +++ b/kameo-actors/src/main.rs @@ -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 for HelloWorldActor { +impl Message 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 for CalculActor { + type Reply = (); + + async fn handle(&mut self, Add(value): Add, _: Context<'_, Self, Self::Reply>) -> Self::Reply { + self.value += value; + } +} + +impl Message for CalculActor { + type Reply = (); + + async fn handle(&mut self, Sub(value): Sub, _: Context<'_, Self, Self::Reply>) -> Self::Reply { + self.value -= value; + } +} + +impl Message for CalculActor { + type Reply = (); + + async fn handle(&mut self, Mul(value): Mul, _: Context<'_, Self, Self::Reply>) -> Self::Reply { + self.value *= value; + } +} + +impl Message
for CalculActor { + type Reply = (); + + async fn handle(&mut self, Div(value): Div, _: Context<'_, Self, Self::Reply>) -> Self::Reply { + self.value /= value; + } +} + +impl Message 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> { - 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(()) }