Skip to content

Commit

Permalink
adds example for emptycallback closing #651
Browse files Browse the repository at this point in the history
Has an explicit comment instructing the user in the use of `move` since thats something people struggle with. I could have made the example nicer and more functional. It could be refactored with a function that generates the callback. Then we would have something like:
```rust
fn new_playlist_pos_callback() -> impl Fn() + Send {
    ...
}

sink.append(song);
sink.append(new_playlist_pos_callback());
sink.append(song);
sink.append(new_playlist_pos_callback());
sink.append(song);
sink.append(new_playlist_pos_callback());
```

I chose instead to keep it as short and simple as possible, even though
the example code on its own is not as usefull now. Functions returning a generic boxed closure are hard to understand and that distracts from what we are trying to show here (how to use the emptycallback source).
  • Loading branch information
dvdsk committed Jan 2, 2025
1 parent ea45c17 commit ed005d4
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions examples/callback_on_end.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::error::Error;
use std::io::BufReader;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

fn main() -> Result<(), Box<dyn Error>> {
let stream_handle = rodio::OutputStreamBuilder::open_default_stream()?;
let sink = rodio::Sink::connect_new(&stream_handle.mixer());

let file = std::fs::File::open("assets/music.wav")?;
sink.append(rodio::Decoder::new(BufReader::new(file))?);

// lets increment a number after `music.wav` has played. We are going to use atomics
// however you could also use a `Mutex` or send a message through a `std::sync::mpsc`.
let playlist_pos = Arc::new(AtomicU32::new(0));

// The closure needs to own everything it uses. We move a clone of
// playlist_pos into the closure. That way we can still access playlist_pos
// after appending the EmptyCallback.
let playlist_pos_clone = playlist_pos.clone();
sink.append(rodio::source::EmptyCallback::<f32>::new(Box::new(
move || {
println!("empty callback is now running");
playlist_pos_clone.fetch_add(1, Ordering::Relaxed);
},
)));

assert_eq!(playlist_pos.load(Ordering::Relaxed), 0);
println!(
"playlist position is: {}",
playlist_pos.load(Ordering::Relaxed)
);
sink.sleep_until_end();
assert_eq!(playlist_pos.load(Ordering::Relaxed), 1);
println!(
"playlist position is: {}",
playlist_pos.load(Ordering::Relaxed)
);

Ok(())
}

0 comments on commit ed005d4

Please sign in to comment.