Skip to content

Commit c1251c1

Browse files
committed
feat: implement spawn_listener for threads.
tries to mimic signature of tasks::spawn_listener with only difference being this function accepts any type that can be converted into an iterator.
1 parent 7af72c4 commit c1251c1

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

concurrency/src/threads/stream.rs

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,36 @@
1-
use crate::threads::{GenServer, GenServerHandle};
1+
use std::thread::JoinHandle;
22

3-
use futures::Stream;
3+
use crate::threads::{GenServer, GenServerHandle};
44

55
/// Spawns a listener that listens to a stream and sends messages to a GenServer.
66
///
77
/// Items sent through the stream are required to be wrapped in a Result type.
8-
pub fn spawn_listener<T, F, S, I, E>(_handle: GenServerHandle<T>, _message_builder: F, _stream: S)
8+
pub fn spawn_listener<T, I>(mut handle: GenServerHandle<T>, stream: I) -> JoinHandle<()>
99
where
10-
T: GenServer + 'static,
11-
F: Fn(I) -> T::CastMsg + Send + 'static,
12-
I: Send + 'static,
13-
E: std::fmt::Debug + Send + 'static,
14-
S: Unpin + Send + Stream<Item = Result<I, E>> + 'static,
10+
T: GenServer,
11+
I: IntoIterator<Item = T::CastMsg>,
12+
<I as IntoIterator>::IntoIter: std::marker::Send + 'static,
1513
{
16-
unimplemented!("Unsupported function in threads mode")
14+
let mut iter = stream.into_iter();
15+
let mut cancelation_token = handle.cancellation_token();
16+
let join_handle = spawned_rt::threads::spawn(move || loop {
17+
match iter.next() {
18+
Some(msg) => match handle.cast(msg) {
19+
Ok(_) => tracing::trace!("Message sent successfully"),
20+
Err(e) => {
21+
tracing::error!("Failed to send message: {e:?}");
22+
break;
23+
}
24+
},
25+
None => {
26+
tracing::trace!("Stream finished");
27+
break;
28+
}
29+
}
30+
if cancelation_token.is_cancelled() {
31+
tracing::trace!("GenServer stopped");
32+
break;
33+
}
34+
});
35+
join_handle
1736
}

0 commit comments

Comments
 (0)