pub struct RcConditionalStatefulConsumer<T> { /* private fields */ }Expand description
RcConditionalStatefulConsumer struct
A single-threaded conditional consumer that only executes when a predicate is
satisfied. Uses RcStatefulConsumer and RcPredicate for shared ownership within a
single thread.
This type is typically created by calling RcStatefulConsumer::when() and is
designed to work with the or_else() method to create if-then-else logic.
§Features
- Shared Ownership: Cloneable via
Rc, multiple owners allowed - Single-Threaded: Not thread-safe, cannot be sent across threads
- Conditional Execution: Only consumes when predicate returns
true - No Lock Overhead: More efficient than
ArcConditionalStatefulConsumer
§Examples
use prism3_function::{Consumer, RcStatefulConsumer};
use std::rc::Rc;
use std::cell::RefCell;
let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let conditional = RcStatefulConsumer::new(move |x: &i32| {
l.borrow_mut().push(*x);
})
.when(|x: &i32| *x > 0);
let conditional_clone = conditional.clone();
let mut value = 5;
let mut m = conditional;
m.accept(&value);
assert_eq!(*log.borrow(), vec![5]);§Author
Haixing Hu
Implementations§
Source§impl<T> RcConditionalStatefulConsumer<T>where
T: 'static,
impl<T> RcConditionalStatefulConsumer<T>where
T: 'static,
Sourcepub fn and_then<C>(&self, next: C) -> RcStatefulConsumer<T>where
C: StatefulConsumer<T> + 'static,
pub fn and_then<C>(&self, next: C) -> RcStatefulConsumer<T>where
C: StatefulConsumer<T> + 'static,
Chains another consumer in sequence
Combines the current conditional consumer with another consumer into a new consumer that implements the following semantics:
When the returned consumer is called with an argument:
- First, it checks the predicate of this conditional consumer
- If the predicate is satisfied, it executes the internal consumer of this conditional consumer
- Then, regardless of whether the predicate was satisfied,
it unconditionally executes the
nextconsumer
In other words, this creates a consumer that conditionally executes the first action (based on the predicate), and then always executes the second action.
§Parameters
next- The next consumer to execute (always executed)
§Returns
Returns a new combined consumer
§Examples
use std::sync::atomic::{AtomicI32, Ordering};
let result = AtomicI32::new(0);
let consumer1 = ArcConsumer::new(|x: &i32| {
result.fetch_add(*x, Ordering::SeqCst);
});
let consumer2 = ArcConsumer::new(|x: &i32| {
result.fetch_add(2 * (*x), Ordering::SeqCst);
});
let conditional = consumer1.when(|x| *x > 0);
let chained = conditional.and_then(consumer2);
chained.accept(&5); // result = 5 + (2*5) = 15
result.store(0, Ordering::SeqCst); // reset
chained.accept(&-5); // result = 0 + (2*-5) = -10 (not -15!)