ImTheSquid
ImTheSquid

Reputation: 405

Calling async functions within an Actix Web WebSocket Interval

I'm trying to run async code within an Actix Web WebSocket interval, but I can't figure out how to do so. I read this question, but I'm not sure if I should take the same approach to my problem as it is slightly different in terms of its design and execution. Here is my code:

struct WebSocket {
    data: Data<State>,
    user: ID,
}

const POLL_INTERVAL: Duration = Duration::from_millis(5);

impl Actor for WebSocket {
    type Context = WebsocketContext<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_interval(POLL_INTERVAL, |myself, ctx| {
            // let fut = ws_poll(myself.user, &myself.data.event_client);

            // fut.into_actor(myself).spawn(ctx);
            // I want to do async stuff in here
            // my_async_fn().await;
        });
    }
}

impl StreamHandler<Result<Message, ProtocolError>> for WebSocket {
    fn handle(&mut self, item: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
        match item.unwrap() {
            Message::Text(txt) => match serde_json::from_str::<WebSocketMessage>(&txt.to_string()).unwrap() {
                WebSocketMessage::SendChatMessage { chat, message } => {}
                WebSocketMessage::ReadChat(chat) => {}
                WebSocketMessage::Typing(chat) => {}
                _ => panic!()
            }
            Message::Ping(msg) => ctx.pong(msg.as_ref()),
            Message::Close(_) => todo!(),
            _ => panic!(),
        }
    }
}

#[get("/ws")]
async fn ws_index(data: Data<State>, user: AuthedUser, r: HttpRequest, stream: Payload) -> WebResult<HttpResponse> {
    ws::start(WebSocket { data, user: user.id }, &r, stream)
}

pub fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(ws_index);
}

Upvotes: 1

Views: 592

Answers (1)

Njuguna Mureithi
Njuguna Mureithi

Reputation: 3856

You are looking for actix::spawn

ctx.run_interval(POLL_INTERVAL, |myself, ctx| {
    // I want to do async stuff in here
    actix::spawn(async { my_async_fn().await; });
});

Upvotes: 0

Related Questions