Callback

Trait Callback 

Source
pub trait Callback<T>: Debug
where T: Debug + Send + Sync,
{ // Required methods fn subscribe(&self) -> Subscription<T>; fn subscribe_with(&self, subscriber: Subscriber<T>); }
Expand description

Allows adding callbacks to the struct. The struct will inform the Subscription when a certain event occurs.

§Example

use std::sync::Arc;
use tokio::runtime::Runtime;
use fx_callback::{Callback, MultiThreadedCallback};

#[derive(Debug)]
pub enum MyEvent {
    Foo,
    Bar,
}

async fn register_callback() {
    let callback = MultiThreadedCallback::<MyEvent>::new();
    let mut receiver = callback.subscribe();

    let event = receiver.recv().await.unwrap();
    // do something with the event
}

Required Methods§

Source

fn subscribe(&self) -> Subscription<T>

Subscribe to the interested event. This creates a new Subscription that will be invoked with a shared instance of the event when the interested event occurs.

§Example
use fx_callback::Callback;

#[derive(Debug, Clone, PartialEq)]
pub enum MyEvent {
    Foo,
}

async fn example(callback: &dyn Callback<MyEvent>) {
    let mut receiver = callback.subscribe();
     
    if let Some(event) = receiver.recv().await {
        // do something with the event
    }
}
§Returns

It returns a Subscription which can be dropped to remove the callback.

Source

fn subscribe_with(&self, subscriber: Subscriber<T>)

Subscribe to the interested event with a Subscriber. This creates an underlying new subscription which will be invoked with the given subscriber when the interested event occurs.

§Remarks

It is possible to grant multiple subscriptions from the same source to the same interested event, as the Callback is only a holder for the Subscription and can’t detect any duplicates.

Implementors§

Source§

impl<T> Callback<T> for MultiThreadedCallback<T>
where T: Debug + Send + Sync,

Source§

impl<T> Callback<T> for SingleThreadedCallback<T>
where T: Debug + Send + Sync,