Updating the message

We will start with updating the message. Add a RepeaterUpdate struct that wraps a NewComment type:

#[derive(Clone)]
pub struct RepeaterUpdate(pub NewComment);

As you can see, we also derived the Clone trait, because we need to clone this message to resend it to multiple subscribers. NewComment also has to be cloneable now.

Let's implement the Message trait for the RepeaterUpdate struct. We will use an empty type for the Result associated type, because we don't care about the delivery of these messages:

impl Message for RepeaterUpdate {
type Result = ();
}

Now, we can implement a Handler for the RepeaterUpdate message type:

impl Handler<RepeaterUpdate> for RepeaterActor {
type Result = ();

fn handle(&mut self, msg: RepeaterUpdate, _: &mut Self::Context) -> Self::Result {
for listener in &self.listeners {
listener.do_send(msg.clone()).ok();
}
}
}

The algorithm of the handler is simple: it iterates over all listeners (actually, addresses of listeners stored as Recipient instances) and sends a cloned message to them. In other words, this actor receives a message and immediately sends it to all known listeners.

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

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