sodium_rust/
stream_sink.rs

1use crate::impl_::stream_sink::StreamSink as StreamSinkImpl;
2use crate::sodium_ctx::SodiumCtx;
3use crate::stream::Stream;
4
5/// A [`Stream`] that allows values to be pushed into it, acting as an
6/// interface between the world of I/O and the world of FRP.
7///
8/// ## Note: This should only be used from _outside_ the context of
9/// the Sodium system to inject data from I/O into the reactive system.
10pub struct StreamSink<A> {
11    pub impl_: StreamSinkImpl<A>,
12}
13
14impl<A> Clone for StreamSink<A> {
15    fn clone(&self) -> Self {
16        StreamSink {
17            impl_: self.impl_.clone(),
18        }
19    }
20}
21
22impl<A: Clone + Send + 'static> StreamSink<A> {
23    /// Create a `StreamSink` that allows calling `send` on it once
24    /// per transaction.
25    ///
26    /// If you call `send` more than once in a transaction on a
27    /// `StreamSink` constructed with `StreamSink::new` it will
28    /// panic. If you need to do this then use
29    /// [`StreamSink::new_with_coalescer`].
30    pub fn new(sodium_ctx: &SodiumCtx) -> StreamSink<A> {
31        StreamSink {
32            impl_: StreamSinkImpl::new(&sodium_ctx.impl_),
33        }
34    }
35
36    /// Create a `StreamSink` that allows calling `send` one or more
37    /// times per transaction.
38    ///
39    /// If you call `send` on the returned `StreamSink` more than once
40    /// in a single transaction the events will be combined into a
41    /// single event using the specified combining function. The
42    /// combining function should be _associative_.
43    pub fn new_with_coalescer<COALESCER: FnMut(&A, &A) -> A + Send + 'static>(
44        sodium_ctx: &SodiumCtx,
45        coalescer: COALESCER,
46    ) -> StreamSink<A> {
47        StreamSink {
48            impl_: StreamSinkImpl::new_with_coalescer(&sodium_ctx.impl_, coalescer),
49        }
50    }
51
52    /// Return a [`Stream`] that can be used in the creation of Sodium
53    /// logic that will consume events pushed into this `StreamSink`
54    /// from the I/O world.
55    pub fn stream(&self) -> Stream<A> {
56        Stream {
57            impl_: self.impl_.stream(),
58        }
59    }
60
61    /// Send a value to be made available to consumers of the `Stream`
62    /// associated with this `StreamSink`.
63    ///
64    /// This method may not be called in handlers registered with
65    /// [`Stream::listen`] or [`Cell::listen`][crate::Cell::listen].
66    pub fn send(&self, a: A) {
67        self.impl_.send(a);
68    }
69}