Any way to cartesian product two futures_channel::mpsc::Receiver?

I tried existed posts, and found solutions for iterators, seems not solutions to my problem;
Currently, I tried collect one receiver and pop the other receiver to create production;
Seems a waste of time to wait collect end;
Any suggections for me?
Here is the code snippet

        let CartesianProductExecutor {
            mut output,
            input_left,
            mut input_right,
        } = *self;

        let left = input_left.collect::<Vec<_>>().await;
        while let Some(row) = input_right.next().await {
            for l in left.iter() {
                let mut row = row.clone();
                row.extend(l.to_owned());
                output.send(row).await?;
            }
        }

Fundamentally, youโ€™ll need to keep O(n) of state information in order to calculate the Cartesian productโ€” That means something like Vec.

If you need the rows in the usual order, thereโ€™s no way to avoid consuming all of one channel before returning the first result. If the output order doesnโ€™t matter to you, though, you can write a streaming version:

  • Initialize 2 empty Vecs ๐“ and ๐“‡
  • For every item ๐“ to arrive from either input channel (via select or similar):
    • If the item came from the left channel
      • For every item ๐“Ž in ๐“‡, yield (๐“, ๐“Ž)
      • Push ๐“ onto ๐“
    • If the item came from the right channel
      • For every item ๐“Ž in ๐“, yield (๐“Ž, ๐“)
      • Push ๐“ onto ๐“‡
5 Likes

Thank you for your advice, seems it's already the best solution for me.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.