Skip to content
Discussion options

You must be logged in to vote

You can make a type that implements Drop and hold that until the stream closes. Doing that with async-stream is quite easy:

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    struct Guard {
        // whatever state you need here
    }

    impl Drop for Guard {
        fn drop(&mut self) {
            tracing::info!("stream closed");
        }
    }

    let stream = async_stream::stream! {
        let _guard = Guard {};
        let mut interval = tokio::time::interval(Duration::from_secs(1));
        loop {
            interval.tick().await;
            yield Ok(Event::default().data("hi"));
        }
        // `_guard` is dropped
    };

    Sse::new(st…

Replies: 4 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@tmpfs
Comment options

Answer selected by tmpfs
Comment options

You must be logged in to vote
1 reply
@davidpdrsn
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants