pub trait StreamHandler<I>
where Self: Actor,
{ // Required method fn handle(&mut self, item: I, ctx: &mut Self::Context); // Provided methods fn started(&mut self, ctx: &mut Self::Context) { ... } fn finished(&mut self, ctx: &mut Self::Context) { ... } fn add_stream<S>(stream: S, ctx: &mut Self::Context) -> SpawnHandle where S: Stream + 'static, Self: StreamHandler<S::Item>, Self::Context: AsyncContext<Self> { ... } }
Expand description

Stream handling for Actors.

This is helper trait that allows handling Streams in a similar way to normal actor messages. When stream resolves its next item, handle() is called with that item.

When the stream completes, finished() is called. By default, it stops Actor execution.

§Examples

use actix::prelude::*;
use futures_util::stream::once;

#[derive(Message)]
#[rtype(result = "()")]
struct Ping;

struct MyActor;

impl StreamHandler<Ping> for MyActor {
    fn handle(&mut self, item: Ping, ctx: &mut Context<MyActor>) {
        println!("PING");
        System::current().stop()
    }

    fn finished(&mut self, ctx: &mut Self::Context) {
        println!("finished");
    }
}

impl Actor for MyActor {
   type Context = Context<Self>;

   fn started(&mut self, ctx: &mut Context<Self>) {
       Self::add_stream(once(async { Ping }), ctx);
   }
}

#[actix::main]
async fn main() {
    MyActor.start();
}

Required Methods§

source

fn handle(&mut self, item: I, ctx: &mut Self::Context)

Called for every message emitted by the stream.

Provided Methods§

source

fn started(&mut self, ctx: &mut Self::Context)

Called when stream emits first item.

Default implementation does nothing.

source

fn finished(&mut self, ctx: &mut Self::Context)

Called when stream finishes.

Default implementation stops Actor execution.

source

fn add_stream<S>(stream: S, ctx: &mut Self::Context) -> SpawnHandle
where S: Stream + 'static, Self: StreamHandler<S::Item>, Self::Context: AsyncContext<Self>,

Register a Stream to the actor context.

Object Safety§

This trait is not object safe.

Implementors§