From 4cca09ce19e3e0cd5c20c16b54a4795b34ef0e6b Mon Sep 17 00:00:00 2001 From: Dongdong Zhou Date: Sun, 13 Aug 2023 17:37:31 +0100 Subject: [PATCH] add update signal from channel --- src/ext_event.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/ext_event.rs b/src/ext_event.rs index 9c1569e1..f63830a6 100644 --- a/src/ext_event.rs +++ b/src/ext_event.rs @@ -3,7 +3,7 @@ use std::{ sync::Arc, }; -use floem_reactive::{create_effect, untrack, with_scope, ReadSignal, Scope, Trigger}; +use floem_reactive::{create_effect, untrack, with_scope, ReadSignal, Scope, Trigger, WriteSignal}; use glazier::{IdleHandle, IdleToken}; // use leptos_reactive::{create_signal, create_trigger, untrack, ReadSignal, SignalSet, Trigger}; use once_cell::sync::Lazy; @@ -71,6 +71,44 @@ pub fn create_ext_action( } } +pub fn update_signal_from_channel( + writer: WriteSignal>, + rx: crossbeam_channel::Receiver, +) { + let cx = Scope::new(); + let trigger = cx.create_trigger(); + let current_view_id = get_current_view(); + + let channel_closed = cx.create_rw_signal(false); + let data = Arc::new(Mutex::new(VecDeque::new())); + + { + let data = data.clone(); + cx.create_effect(move |_| { + trigger.track(); + while let Some(value) = data.lock().pop_front() { + writer.set(value); + } + + if channel_closed.get() { + cx.dispose(); + } + }); + } + + let send = create_ext_action(cx, move |_| { + channel_closed.set(true); + }); + + std::thread::spawn(move || { + while let Ok(event) = rx.recv() { + data.lock().push_back(Some(event)); + EXT_EVENT_HANDLER.add_trigger(current_view_id, trigger); + } + send(()); + }); +} + pub fn create_signal_from_channel( rx: crossbeam_channel::Receiver, ) -> ReadSignal> {