Skip to content

Commit 4eb96b1

Browse files
committed
improv: file watch subscription
1 parent a174744 commit 4eb96b1

1 file changed

Lines changed: 12 additions & 15 deletions

File tree

src/app.rs

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use slotmap::Key as SlotMapKey;
3030
use std::any::TypeId;
3131
use std::collections::{HashMap, VecDeque};
3232
use std::path::{Path, PathBuf};
33-
use std::sync::{Arc, Mutex};
33+
use std::sync::Arc;
3434
use widgets::{TextEditor, text_editor};
3535

3636
pub mod app_menu;
@@ -1330,10 +1330,10 @@ fn cedilla_main_view<'a>(
13301330
}
13311331
}
13321332

1333-
/// Watches for external changes on the currently open file
1333+
// Watches for external changes on the currently open file
13341334
fn file_watch_subscription(path: Option<PathBuf>) -> Subscription<Message> {
13351335
use cosmic::iced::futures::SinkExt;
1336-
use cosmic::iced_futures::futures::channel::mpsc;
1336+
use cosmic::iced_futures::futures::channel::mpsc as iced_mpsc;
13371337
use notify::{EventKind, RecursiveMode, Watcher, recommended_watcher};
13381338

13391339
let Some(path) = path else {
@@ -1345,9 +1345,8 @@ fn file_watch_subscription(path: Option<PathBuf>) -> Subscription<Message> {
13451345

13461346
cosmic::iced_futures::stream::channel(
13471347
16,
1348-
move |mut output: mpsc::Sender<Message>| async move {
1349-
let (tx, rx) = std::sync::mpsc::channel::<PathBuf>();
1350-
let rx = Arc::new(Mutex::new(rx));
1348+
move |mut output: iced_mpsc::Sender<Message>| async move {
1349+
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<PathBuf>();
13511350

13521351
let mut watcher =
13531352
match recommended_watcher(move |res: notify::Result<notify::Event>| {
@@ -1373,24 +1372,22 @@ fn file_watch_subscription(path: Option<PathBuf>) -> Subscription<Message> {
13731372
return;
13741373
}
13751374

1375+
// keep the watcher alive
13761376
let _watcher = watcher;
13771377

13781378
loop {
1379-
let rx2 = Arc::clone(&rx);
1380-
let changed_path =
1381-
match tokio::task::spawn_blocking(move || rx2.lock().unwrap().recv()).await
1382-
{
1383-
Ok(Ok(p)) => p,
1384-
_ => return,
1385-
};
1379+
let changed_path = match rx.recv().await {
1380+
Some(p) => p,
1381+
None => return, // channel closed, exit the stream
1382+
};
13861383

13871384
if changed_path == path_owned {
13881385
let _ = output
1389-
.send(Message::ExternalFileChanged(changed_path))
1386+
.send(Message::ExternalFileChanged(changed_path.clone()))
13901387
.await;
13911388

13921389
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1393-
while rx.lock().unwrap().try_recv().is_ok() {}
1390+
while rx.try_recv().is_ok() {}
13941391
}
13951392
}
13961393
},

0 commit comments

Comments
 (0)