Actors

We will add an actor to resend messages to other actors. We need some basic types from the actix crate, along with a HashSet to keep addresses of actors. Import the NewComment struct, which we will clone and resend:

use actix::{Actor, Context, Handler, Message, Recipient};
use std::collections::HashSet;
use super::NewComment;

Add a RepeaterActor struct with a listeners field of the HashSet type that contains Recipient instances:

pub struct RepeaterActor {
listeners: HashSet<Recipient<RepeaterUpdate>>,
}

You are familiar with the Addr type, but we haven't used Recipient before. Actually, you can convert any Addr instance into a Recipient using the recipient method call. The Recipient type is an address that supports only one type of Message.

Add a constructor that creates an empty HashSet:

impl RepeaterActor {
pub fn new() -> Self {
Self {
listeners: HashSet::new(),
}
}
}

Next, implement an Actor trait for this struct:

impl Actor for RepeaterActor {
type Context = Context<Self>;
}

It's enough to have a standard Context type as an associated context type of Actor, because it can work asynchronously.

Now, we have to add messages to this actor type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.58.194