Skip to content

Commit

Permalink
Use more idiomatic interface for AsyncReceiver
Browse files Browse the repository at this point in the history
  • Loading branch information
daxpedda committed Mar 16, 2023
1 parent 9ee9a5e commit f579aee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
24 changes: 13 additions & 11 deletions src/platform_impl/web/event_loop/proxy.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::future::Future;
use std::pin::Pin;
use std::future;
use std::rc::Rc;
use std::sync::mpsc::{self, Receiver, RecvError, SendError, Sender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::task::{Poll, Waker};

use crate::event_loop::EventLoopClosed;

Expand Down Expand Up @@ -39,7 +39,10 @@ pub fn channel<T: 'static>() -> (AsyncSender<T>, AsyncReceiver<T>) {
sender,
waker: Arc::clone(&waker),
};
let receiver = AsyncReceiver { receiver, waker };
let receiver = AsyncReceiver {
receiver: Rc::new(receiver),
waker,
};

(sender, receiver)
}
Expand Down Expand Up @@ -71,15 +74,13 @@ impl<T: 'static> Clone for AsyncSender<T> {
}

pub struct AsyncReceiver<T: 'static> {
receiver: Receiver<T>,
receiver: Rc<Receiver<T>>,
waker: Arc<Mutex<Option<Waker>>>,
}

impl<T: 'static> Future for AsyncReceiver<T> {
type Output = Result<T, RecvError>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.receiver.try_recv() {
impl<T: 'static> AsyncReceiver<T> {
pub async fn next(&mut self) -> Result<T, RecvError> {
future::poll_fn(|cx| match self.receiver.try_recv() {
Ok(event) => Poll::Ready(Ok(event)),
Err(TryRecvError::Empty) => {
*self.waker.lock().unwrap() = Some(cx.waker().clone());
Expand All @@ -91,6 +92,7 @@ impl<T: 'static> Future for AsyncReceiver<T> {
}
}
Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)),
}
})
.await
}
}
2 changes: 1 addition & 1 deletion src/platform_impl/web/event_loop/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl<T: 'static> Shared<T> {
wasm_bindgen_futures::spawn_local({
let runner = this.clone();
async move {
while let Ok(value) = (&mut proxy_receiver).await {
while let Ok(value) = proxy_receiver.next().await {
runner.send_event(Event::UserEvent(value))
}

Expand Down

0 comments on commit f579aee

Please sign in to comment.