pub trait Service:
Sized
+ Send
+ 'static {
// Provided methods
fn started(&mut self, ctx: &mut ServiceContext<Self>) { ... }
fn start(self) -> Link<Self> { ... }
fn create<F>(action: F) -> Link<Self>
where F: FnOnce(&mut ServiceContext<Self>) -> Self { ... }
fn stopping(&mut self) { ... }
}
Expand description
Trait implemented by structures that can be spawned as services and used by the app
Provided Methods§
Sourcefn started(&mut self, ctx: &mut ServiceContext<Self>)
fn started(&mut self, ctx: &mut ServiceContext<Self>)
Handler called before the service starts processing messages
ctx
The service context
Sourcefn start(self) -> Link<Self>
fn start(self) -> Link<Self>
Start an already created service and provides a link for communicating with the service
use interlink::prelude::*;
#[derive(Service)]
struct MyService;
#[tokio::main]
async fn main() {
// Create the service
let service: MyService = MyService {};
// Start the service and obtain a link to it
let addr: Link<MyService> = service.start();
}
Sourcefn create<F>(action: F) -> Link<Self>where
F: FnOnce(&mut ServiceContext<Self>) -> Self,
fn create<F>(action: F) -> Link<Self>where
F: FnOnce(&mut ServiceContext<Self>) -> Self,
Alternative way of creating a service where the service may rely on the context an example of this is an associated service which requires a link to the service but is also stored on the service struct
use interlink::prelude::*;
#[derive(Service)]
struct First {
/// Link to spawned service
second: Link<Second>,
}
/// Some other service which requires a link to our service
#[derive(Service)]
struct Second {
/// Link to the service that owns this service
owner: Link<First>
}
#[tokio::main]
async fn main() {
// Provide a closure which takes in the ctx
let link: Link<First> = First::create(|ctx| {
// Create second which references the context
let second: Link<Second> = Second {
owner: ctx.link()
}
.start();
// Can now use the spawned value
First { second }
});
}
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.