Skip to content

Commit

Permalink
Add tokio channel behind flag (#483)
Browse files Browse the repository at this point in the history
  • Loading branch information
jrmoulton committed May 31, 2024
1 parent 1674b04 commit 959e292
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ taffy = { version = "0.4", features = ["grid"] }
rfd = { version = "0.14.0", default-features = false, features = [
"xdg-portal",
], optional = true }
tokio = { version = "1", features = ["sync", "rt"], optional = true }
raw-window-handle = { workspace = true }
unicode-segmentation = "1.10.0"
peniko = { workspace = true }
Expand Down Expand Up @@ -93,6 +94,8 @@ image-tga = ["image/tga"]
image-tiff = ["image/tiff"]
image-webp = ["image/webp"]

tokio = ["dep:tokio"]

# rfd (file dialog) async runtime
rfd-async-std = ["dep:rfd", "rfd/async-std"]
rfd-tokio = ["dep:rfd", "rfd/tokio"]
40 changes: 40 additions & 0 deletions src/ext_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,43 @@ pub fn create_signal_from_channel<T: Send + 'static>(

read
}

#[cfg(feature = "tokio")]
pub fn create_signal_from_tokio_channel<T: Send + 'static>(
mut rx: tokio::sync::mpsc::UnboundedReceiver<T>,
) -> ReadSignal<Option<T>> {
let cx = Scope::new();
let trigger = cx.create_trigger();

let channel_closed = cx.create_rw_signal(false);
let (read, write) = cx.create_signal(None);
let data = std::sync::Arc::new(std::sync::Mutex::new(VecDeque::new()));

{
let data = data.clone();
cx.create_effect(move |_| {
trigger.track();
while let Some(value) = data.lock().unwrap().pop_front() {
write.set(value);
}

if channel_closed.get() {
cx.dispose();
}
});
}

let send = create_ext_action(cx, move |_| {
channel_closed.set(true);
});

tokio::spawn(async move {
while let Some(event) = rx.recv().await {
data.lock().unwrap().push_back(Some(event));
crate::ext_event::register_ext_trigger(trigger);
}
send(());
});

read
}

0 comments on commit 959e292

Please sign in to comment.