Addr

Struct Addr 

Source
pub struct Addr<A> { /* private fields */ }
Expand description

The address of an actor.

When all references to Addr<A> are dropped, the actor ends. You can use Clone trait to create multiple copies of Addr<A>.

Implementations§

Source§

impl<A> Addr<A>

Source

pub fn downgrade(&self) -> WeakAddr<A>

Source§

impl<A: Actor> Addr<A>

Source

pub fn actor_id(&self) -> ActorId

Returns the id of the actor.

Source

pub fn stop(&mut self, err: Option<Error>) -> Result<()>

Stop the actor.

Source

pub async fn call<T: Message>(&self, msg: T) -> Result<T::Result>
where A: Handler<T>,

Send a message msg to the actor and wait for the return value.

Examples found in repository?
examples/ping.rs (line 30)
25async fn main() -> Result<()> {
26    // start new actor
27    let addr = MyActor { count: 10 }.start().await?;
28
29    // send message and get future for result
30    let res = addr.call(Ping(10)).await?;
31    println!("RESULT: {}", res == 20);
32
33    Ok(())
34}
Source

pub fn send<T: Message<Result = ()>>(&self, msg: T) -> Result<()>
where A: Handler<T>,

Send a message msg to the actor without waiting for the return value.

Examples found in repository?
examples/subscriber.rs (line 36)
34    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
35        println!("Subscriber Parent Started");
36        let _ = ctx.address().send(InitializeChildSubscribers);
37        Ok(())
38    }
39}
40
41#[message]
42struct InitializeChildSubscribers;
43
44#[async_trait::async_trait]
45impl Handler<InitializeChildSubscribers> for SubscriberParent {
46    async fn handle(&mut self, _ctx: &mut Context<Self>, _msg: InitializeChildSubscribers) {
47        let message_producer_addr = self.message_producer.clone();
48        let dummy_ids: Vec<i32> = vec![1, 2, 3, 4, 5];
49        let children_unstarted_actors_vec = dummy_ids.into_iter().map(move |id| {
50            let id = id.clone();
51            let addr = message_producer_addr.clone();
52
53            Subscriber::new(id, addr)
54        });
55
56        let children_addr_vec = children_unstarted_actors_vec
57            .into_iter()
58            .map(|actor| async { actor.start().await.unwrap() });
59
60        let children_addr_vec = futures::future::join_all(children_addr_vec).await;
61
62        self.children_subscribers = children_addr_vec;
63    }
64}
65
66#[message]
67struct ClearChildSubscribers;
68
69#[async_trait::async_trait]
70impl Handler<ClearChildSubscribers> for SubscriberParent {
71    async fn handle(&mut self, _ctx: &mut Context<Self>, _msg: ClearChildSubscribers) {
72        self.children_subscribers = Vec::new();
73    }
74}
75
76// (Child) Subscriber - B
77
78struct Subscriber {
79    id: i32,
80    message_producer_addr: Addr<MessageProducer>,
81}
82
83impl Subscriber {
84    fn new(id: i32, message_producer_addr: Addr<MessageProducer>) -> Subscriber {
85        Subscriber {
86            id,
87            message_producer_addr,
88        }
89    }
90}
91
92#[async_trait::async_trait]
93impl Actor for Subscriber {
94    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
95        // Send subscription request message to the Message Producer
96        println!("Child Subscriber Started - id {:?}", self.id);
97        let self_sender = ctx.address().sender();
98        let _ = self.message_producer_addr.send(SubscribeToProducer {
99            sender: self_sender,
100        });
101        Ok(())
102    }
More examples
Hide additional examples
examples/supervisor_clear_send_later.rs (line 53)
43async fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let service_supervisor = xactor::Supervisor::start(PingLater::default).await?;
45    let service_addr = service_supervisor.clone();
46
47    let supervisor_task = xactor::spawn(async {
48        service_supervisor.wait_for_stop().await;
49    });
50
51    let send_ping = async {
52        println!("  main  :: sending Ping");
53        service_addr.send(Ping("before halt")).unwrap();
54    };
55
56    let send_halt = async {
57        xactor::sleep(Duration::from_millis(1_000)).await;
58        println!("  main  :: sending Halt");
59        service_addr.send(Halt).unwrap();
60    };
61
62    let _ = futures::join!(supervisor_task, send_halt, send_ping);
63
64    Ok(())
65}
examples/supervisor_clear_interval.rs (line 79)
68async fn main() -> Result<(), Box<dyn std::error::Error>> {
69    let service_supervisor = xactor::Supervisor::start(PingTimer::default).await?;
70    let service_addr = service_supervisor.clone();
71
72    let supervisor_task = xactor::spawn(async {
73        service_supervisor.wait_for_stop().await;
74    });
75
76    let send_halt = async {
77        xactor::sleep(Duration::from_millis(5_200)).await;
78        println!("  main  :: sending Halt");
79        service_addr.send(Halt).unwrap();
80    };
81
82    let _ = futures::join!(supervisor_task, send_halt);
83    // run this to see that the interval is not properly stopped if the ctx is stopped
84    // futures::join!(supervisor_task, send_panic); // there is no panic recovery
85
86    Ok(())
87}
Source

pub fn caller<T: Message>(&self) -> Caller<T>
where A: Handler<T>,

Create a Caller<T> for a specific message type

Source

pub fn sender<T: Message<Result = ()>>(&self) -> Sender<T>
where A: Handler<T>,

Create a Sender<T> for a specific message type

Examples found in repository?
examples/subscriber.rs (line 97)
94    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
95        // Send subscription request message to the Message Producer
96        println!("Child Subscriber Started - id {:?}", self.id);
97        let self_sender = ctx.address().sender();
98        let _ = self.message_producer_addr.send(SubscribeToProducer {
99            sender: self_sender,
100        });
101        Ok(())
102    }
Source

pub async fn wait_for_stop(self)

Wait for an actor to finish, and if the actor has finished, the function returns immediately.

Examples found in repository?
examples/main.rs (line 30)
27async fn main() -> Result<()> {
28    // Exit the program after 3 seconds
29    let addr = MyActor.start().await?;
30    addr.wait_for_stop().await;
31    Ok(())
32}
More examples
Hide additional examples
examples/subscriber.rs (line 12)
10async fn main() -> std::io::Result<()> {
11    let parent_addr = SubscriberParent::new().await.start().await.unwrap();
12    parent_addr.wait_for_stop().await;
13    Ok(())
14}
examples/supervisor_clear_send_later.rs (line 48)
43async fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let service_supervisor = xactor::Supervisor::start(PingLater::default).await?;
45    let service_addr = service_supervisor.clone();
46
47    let supervisor_task = xactor::spawn(async {
48        service_supervisor.wait_for_stop().await;
49    });
50
51    let send_ping = async {
52        println!("  main  :: sending Ping");
53        service_addr.send(Ping("before halt")).unwrap();
54    };
55
56    let send_halt = async {
57        xactor::sleep(Duration::from_millis(1_000)).await;
58        println!("  main  :: sending Halt");
59        service_addr.send(Halt).unwrap();
60    };
61
62    let _ = futures::join!(supervisor_task, send_halt, send_ping);
63
64    Ok(())
65}
examples/supervisor_clear_interval.rs (line 73)
68async fn main() -> Result<(), Box<dyn std::error::Error>> {
69    let service_supervisor = xactor::Supervisor::start(PingTimer::default).await?;
70    let service_addr = service_supervisor.clone();
71
72    let supervisor_task = xactor::spawn(async {
73        service_supervisor.wait_for_stop().await;
74    });
75
76    let send_halt = async {
77        xactor::sleep(Duration::from_millis(5_200)).await;
78        println!("  main  :: sending Halt");
79        service_addr.send(Halt).unwrap();
80    };
81
82    let _ = futures::join!(supervisor_task, send_halt);
83    // run this to see that the interval is not properly stopped if the ctx is stopped
84    // futures::join!(supervisor_task, send_panic); // there is no panic recovery
85
86    Ok(())
87}
Source§

impl<T: Message<Result = ()> + Clone> Addr<Broker<T>>

Source

pub fn publish(&mut self, msg: T) -> Result<()>

Publishes a message of the specified type.

Trait Implementations§

Source§

impl<A> Clone for Addr<A>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<A> Hash for Addr<A>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<A> PartialEq for Addr<A>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<A> Freeze for Addr<A>

§

impl<A> !RefUnwindSafe for Addr<A>

§

impl<A> Send for Addr<A>

§

impl<A> Sync for Addr<A>

§

impl<A> Unpin for Addr<A>

§

impl<A> !UnwindSafe for Addr<A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.