Skip to content

async batching of messages in a channel #3589

Answered by Darksonn
barkanido asked this question in Q&A
Discussion options

You must be logged in to vote

Another option is to simply do it manually with tokio::select!.

let mut batch = Vec::new();
let dur = Duration::new(10, 0);
let mut chan_open = true;
while chan_open {
    let timeout = tokio::time::sleep(dur);
    tokio::pin!(timeout);
    while batch.len() < 25 {
        tokio::select! {
            item = chan.recv() => match item {
                Some(item) => batch.push(item),
                None => {
                    // channel is closed
                    chan_open = false;
                    break
                }
            },
            _ = &mut timeout => break,
        }
    }
    
    handle_batch(&mut batch).await;
    batch.clear();
}

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@Darksonn
Comment options

@barkanido
Comment options

@Darksonn
Comment options

Comment options

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