How to Use Waker and Context in Rust Futures

Use Context to register a Waker in your poll method so the executor knows when to resume your future.

You use Context to register a Waker that notifies the executor when a future is ready to resume, and you implement poll_next to return Poll::Pending if data isn't ready yet. The Context passed to your poll method contains the Waker you must call via waker.wake() when the asynchronous operation completes.

use std::pin::Pin;
use std::task::{Context, Poll, Waker};

struct MyStream;

impl Stream for MyStream {
    type Item = String;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // If data is ready, return it
        if let Some(item) = self.get_ready_data() {
            return Poll::Ready(Some(item));
        }

        // Otherwise, register the waker and return Pending
        cx.waker().wake_by_ref(); // Register interest
        Poll::Pending
    }
}