DzenanJupic/rustube

callback cannot use in `tokio::spawn`

Closed this issue · 1 comments

Description

I want to download video in an new task scope, but the Callback not implement Send.

#[tokio::main]
async fn main() -> Result<()> {
    let path = ".";
    let url = "xxxxxx"; // some url
    let id = Id::from_raw(url)?.into_owned();

    let cookie_jar = rustube::fetcher::recommended_cookies();
    let headers = rustube::fetcher::recommended_headers();

    let client = Client::builder()
        .default_headers(headers)
        .cookie_provider(std::sync::Arc::new(cookie_jar))
        .build()
        .unwrap();

    let join_handle = tokio::spawn(async move {
        let video = VideoFetcher::from_id_with_client(id, client.clone())
            .fetch()
            .await
            .unwrap()
            .descramble()
            .unwrap();
        let title = video.title().to_string();

        let callback = Callback::new().connect_on_progress_closure_slow(move |arg| {
            if let Some(content_length) = arg.content_length {
                println!("[{title}] download {}%", (arg.current_chunk * 100) as f64 / content_length as f64);
            }
        });
        let path = video
            .best_quality()
            .ok_or(Error::NoStreams)
            .unwrap()
            .download_to_dir_with_callback(path, callback)
            .await
            .unwrap();
        println!("downloaded video to {:?}", path);
    });

    join_handle.await.unwrap();

    Ok(())
}

will build error error: future cannot be sent between threads safely

future is not `Send` as this value is used across an await
let callback = Callback::new().connect_on_progress_closure_slow(move |arg| {
    |               -------- has type `Callback` which is not `Send`
...
54  |               .download_to_dir_with_callback(path, callback)
    |  ___________________________________________________________^
55  | |             .await
    | |__________________^ await occurs here, with `callback` maybe used later

Version

0.5.0

Hey @umaYnit, thanks for filing this Issue.
I changed Callback to now be Send, so it can be used in such cases.

This is a breaking change, so it's released in 0.6.0 🎉