factor out a hot reloading connect function

This commit is contained in:
= committed 2023-01-11 16:43:41 -06:00
1 parent e5e1abbdac
commit 042b67b61b
11 files changed
+47 -112

No files matched your search

+29 -2
View File
@@ -1,16 +1,18 @@
use std::{
io::Write,
io::{BufRead, BufReader, Write},
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex},
};
use dioxus_core::Template;
pub use dioxus_hot_reload_macro::hot_reload;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::{FileMap, UpdateResult};
use interprocess::local_socket::LocalSocketListener;
use interprocess::local_socket::{LocalSocketListener, LocalSocketStream};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
/// Initialize the hot reloading listener on the given path
pub fn init(path: &'static str) {
if let Ok(crate_dir) = PathBuf::from_str(path) {
let temp_file = std::env::temp_dir().join("@dioxusin");
@@ -82,3 +84,28 @@ pub fn init(path: &'static str) {
}
}
}
/// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected
pub fn connect(mut f: impl FnMut(Template<'static>) + Send + 'static) {
std::thread::spawn(move || {
let temp_file = std::env::temp_dir().join("@dioxusin");
if let Ok(socket) = LocalSocketStream::connect(temp_file.as_path()) {
let mut buf_reader = BufReader::new(socket);
loop {
let mut buf = String::new();
match buf_reader.read_line(&mut buf) {
Ok(_) => {
let template: Template<'static> =
serde_json::from_str(Box::leak(buf.into_boxed_str())).unwrap();
f(template);
}
Err(err) => {
if err.kind() != std::io::ErrorKind::WouldBlock {
break;
}
}
}
}
}
});
}