Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. use actix::prelude::*;
  2.  
  3. /// This actor needs to handle the message.
  4. struct LeafActor;
  5.  
  6. impl Actor for LeafActor {
  7. type Context = Context<Self>;
  8. }
  9.  
  10. /// This actor needs to receive a message, pass it to the leaf actor, and then handle the result
  11. /// from the leaf actor.
  12. struct NodeActor {
  13. leaf_addr: Addr<LeafActor>,
  14. }
  15.  
  16. impl Actor for NodeActor {
  17. type Context = Context<Self>;
  18. }
  19.  
  20. #[derive(Debug)]
  21. struct Msg;
  22.  
  23. #[derive(Debug)]
  24. enum MyError {
  25. /// An actual error that will be returned from the leaf actor.
  26. Logical,
  27. /// Indicating that something went wrong in the mechanism (a.k.a - a mailbox error)
  28. Technical,
  29. }
  30.  
  31. impl Message for Msg {
  32. type Result = Result<(), MyError>;
  33. }
  34.  
  35. impl Handler<Msg> for LeafActor {
  36. type Result = Result<(), MyError>;
  37.  
  38. fn handle(&mut self, msg: Msg, _ctx: &mut Context<Self>) -> Self::Result {
  39. println!("Leaf actor got {:?}", msg);
  40. Err(MyError::Logical)
  41. }
  42. }
  43.  
  44. impl Handler<Msg> for NodeActor {
  45. type Result = ResponseActFuture<Self, (), MyError>;
  46.  
  47. fn handle(&mut self, msg: Msg, _ctx: &mut Context<Self>) -> Self::Result {
  48. println!("Node actor got {:?}", msg);
  49. Box::new(
  50. self.leaf_addr.send(msg).into_actor(self)
  51. .map_err(|error: MailboxError, _, _| {
  52. println!("Got a mailbox error {:?}, but we have to pass a MyError", error);
  53. MyError::Technical
  54. })
  55. .map(|result: Result<(), MyError>, _, _| {
  56. println!("The result node actor got from leaf actor is {:?}, but we can't pass the error", result);
  57. () // this is all we can return here...
  58. })
  59. )
  60. }
  61. }
  62.  
  63. fn main() {
  64. let sys = System::new("my-system");
  65.  
  66. let leaf_addr = LeafActor.start();
  67. let node_addr = NodeActor{leaf_addr}.start();
  68.  
  69. Arbiter::spawn(node_addr.send(Msg)
  70. .map(|response: Result<(), MyError>| {
  71. println!("Main got response from node actor: {:?}", response);
  72. })
  73. .map_err(|error: MailboxError| {
  74. println!("Main got mailbox error from node actor: {:?}", error);
  75. })
  76. );
  77.  
  78. sys.run().unwrap();
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement