From 4846d36777f6bf69dff329413a9dc01e620aef52 Mon Sep 17 00:00:00 2001 From: Jens Reimann Date: Fri, 9 Sep 2022 09:56:32 +0200 Subject: [PATCH] Implement filter_reform for all Callback output types As suggested in the PR, this implements filter_reform for all output types of callbacks by mapping to `Option`. --- packages/yew/src/callback.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/yew/src/callback.rs b/packages/yew/src/callback.rs index 971acb3d960..74982930717 100644 --- a/packages/yew/src/callback.rs +++ b/packages/yew/src/callback.rs @@ -80,21 +80,18 @@ impl Callback { }; Callback::from(func) } -} -impl Callback { /// Creates a new callback from another callback and a function. /// When emitted will call the function and, only if it returns `Some(value)`, will emit /// `value` to the original callback. - pub fn filter_reform(&self, func: F) -> Callback + pub fn filter_reform(&self, func: F) -> Callback> where F: Fn(T) -> Option + 'static, { let this = self.clone(); - let func = move |input| { - if let Some(output) = func(input) { - this.emit(output); - } + let func = move |input| match func(input) { + Some(output) => Some(this.emit(output)), + None => None, }; Callback::from(func) } @@ -109,14 +106,16 @@ mod test { use super::*; /// emit the callback with the provided value - fn emit(values: I, f: F) -> Vec + fn emit(values: I, f: F) -> Vec where I: IntoIterator, - F: FnOnce(Callback) -> Callback, + F: FnOnce(Callback) -> Callback, { let result = Rc::new(Mutex::new(Vec::new())); let cb_result = result.clone(); - let cb = f(Callback::from(move |v| cb_result.lock().unwrap().push(v))); + let cb = f(Callback::::from(move |v| { + cb_result.lock().unwrap().push(v); + })); for value in values { cb.emit(value); }