Отказ от ответственности: я не могу комментировать, если это хороший шаблон проектирования для Actix , так как я только начинаю понимать основы.
Как вы уже обнаружили, проблема связана с требованиями времени жизни.
Для метода Actor::create
для аргумента замыкания требуется время жизни 'static
:
fn create<F>(f: F) -> Addr<Self>
where
Self: Actor<Context = Context<Self>>,
F: FnOnce(&mut Context<Self>) -> Self + 'static,
&self.events[0]
не удовлетворяет требованию 'static
срока службы.
Одним из решений является перенос владения объектом EventManager
на MyActor
:
use actix::*;
use actix_web::ws::{Client, Message, ProtocolError};
use futures::Future;
struct MyActor {
evm: EventManager,
}
impl Actor for MyActor {
type Context = Context<Self>;
}
impl StreamHandler<Message, ProtocolError> for MyActor {
fn handle(&mut self, msg: Message, _ctx: &mut Context<Self>) {
match msg {
Message::Text(text) => {
// just for sake of demo: execute all event handlers
for idx in 0..self.evm.events.len() {
(self.evm.events[idx].handler)(text.clone())
}
}
_ => panic!(),
}
}
}
pub struct Event {
handler: Box<Fn(String) + 'static>,
}
pub struct EventManager {
events: Vec<Event>,
}
impl EventManager {
pub fn new() -> Self {
Self { events: vec![] }
}
pub fn capture<F>(&mut self, function: F)
where
F: Fn(String) + 'static,
{
let event = Event {
handler: Box::new(function),
};
self.events.push(event);
}
pub fn run(self) {
let runner = System::new("example");
Arbiter::spawn(
Client::new("http://127.0.0.1:8080/ws/")
.connect()
.map(|(reader, _writer)| {
MyActor::create(|ctx| {
MyActor::add_stream(reader, ctx);
// move event manager inside the actor
MyActor { evm: self }
});
}).map_err(|err| println!("FATAL: {}", err)),
);
runner.run();
}
}
pub fn ready() {
let mut client = EventManager::new();
client.capture(|data| println!("processing the data: {:?}", data));
client.capture(|data| println!("processing AGAIN the data: {:?}", data));
client.run();
// here run client is not more available: it was moved inside the actor
}
fn main() {
ready();
}