Skip to content

How to select! on a list of Receiver? #7314

Discussion options

You must be logged in to vote

This is my final solution. Thank you very much for telling me the struct SelectAll.

pub struct MultiWatcher<T> {
    watches: Vec<Receiver<T>>,
}

impl<T> MultiWatcher<T> {
    pub fn new(watches: Vec<Receiver<T>>) -> Self {
        Self { watches, }
    }

    pub async fn wait_next_change(&mut self) -> Option<usize> {
        let mut futures = self.watches.iter_mut().map(|a| Box::pin(a.changed())).collect::<Vec<_>>();
        while !futures.is_empty() {
            let (res, index, rest) = futures::future::select_all(futures).await;
            if let Ok(()) = res { return Some(index) }
            futures = rest;
        }
        None
    }
}

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@xuxiaocheng0201
Comment options

@Darksonn
Comment options

@xuxiaocheng0201
Comment options

@xuxiaocheng0201
Comment options

Answer selected by xuxiaocheng0201
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