1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use self::builder::{multi::MultiStreamBuilder, StreamBuilder};
use crate::{exchange::ExchangeId, subscription::SubKind};
use std::collections::HashMap;
use tokio::sync::mpsc;
use tokio_stream::{wrappers::UnboundedReceiverStream, StreamMap};
pub mod builder;
pub mod consumer;
#[derive(Debug)]
pub struct Streams<T> {
pub streams: HashMap<ExchangeId, mpsc::UnboundedReceiver<T>>,
}
impl<T> Streams<T> {
pub fn builder<Kind>() -> StreamBuilder<Kind>
where
Kind: SubKind,
{
StreamBuilder::<Kind>::new()
}
pub fn builder_multi() -> MultiStreamBuilder<T> {
MultiStreamBuilder::<T>::new()
}
pub fn select(&mut self, exchange: ExchangeId) -> Option<mpsc::UnboundedReceiver<T>> {
self.streams.remove(&exchange)
}
pub async fn join(self) -> mpsc::UnboundedReceiver<T>
where
T: Send + 'static,
{
let (joined_tx, joined_rx) = mpsc::unbounded_channel();
for mut exchange_rx in self.streams.into_values() {
let joined_tx = joined_tx.clone();
tokio::spawn(async move {
while let Some(event) = exchange_rx.recv().await {
let _ = joined_tx.send(event);
}
});
}
joined_rx
}
pub async fn join_map(self) -> StreamMap<ExchangeId, UnboundedReceiverStream<T>> {
self.streams
.into_iter()
.fold(StreamMap::new(), |mut map, (exchange, rx)| {
map.insert(exchange, UnboundedReceiverStream::new(rx));
map
})
}
}