pub trait Callback<T>: Debug{
// 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§
Sourcefn subscribe(&self) -> Subscription<T>
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.
Sourcefn subscribe_with(&self, subscriber: Subscriber<T>)
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.