Skip to content

Use a trait-based design for stop-token. #10

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 6 commits into from
Oct 2, 2021
Merged

Use a trait-based design for stop-token. #10

merged 6 commits into from
Oct 2, 2021

Conversation

yoshuawuyts
Copy link
Collaborator

@yoshuawuyts yoshuawuyts commented Sep 24, 2021

Resolves #3, #4.

This PR changes stop-token to use a trait-based API, rather than creating futures directly from StopToken. This sets us up to also be able to generate alternate deadlines from e.g. std::time::{Instant, SystemTime}.

Usage Example

use async_std::prelude::*;
use async_std::{stream, task};

use stop_token::prelude::*;
use stop_token::StopSource;

use std::time::Duration;

#[async_std::main]
async fn main() {
    // Create a stop source and generate a token.
    let src = StopSource::new();
    let stop = src.token();

    // When stop source is dropped, the loop will stop.
    // Move the source to a task, and drop it after 1 sec.
    task::spawn(async move {
        task::sleep(Duration::from_secs(1)).await;
        drop(src);
    });

    // Create a stream that endlessly generates numbers until
    // it receives a signal it needs to stop.
    let mut work = stream::repeat(12u8).until(stop);

    // Loop over each item in the stream.
    while let Some(Ok(ev)) = work.next().await {
        println!("{}", ev);
    }
}

The "shiny future" variant of this I envision (everything in preludes, all part of std, lang features stable) would be closer to this:

use std::{iter, task};

async fn main() {
    let src = task::StopSource::new();
    let stop = src.token();

    task::spawn(async move {
        task::sleep(Duration::from_secs(1)).await;
        drop(src);
    });

    for await? ev in iter::repeat(12u8).until(stop) {
        println!("{}", ev).await;
    }
}

Which I think would be quite nice to use!

@yoshuawuyts yoshuawuyts marked this pull request as ready for review October 2, 2021 12:46
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant