Expand description
A simple wrapper around winit
that allows one to block on a future using the winit
event loop.
winit
does not support async
programming by default. This crate provides a small workaround
that allows one to block on a future using the winit
event loop.
§Examples
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoopBuilder};
use winit::window::WindowBuilder;
use winit_block_on::prelude::*;
use std::future::pending;
use std::time::Duration;
// Create an event loop.
let event_loop = EventLoopBuilder::new_block_on().build();
// Create a window inside the event loop.
let window = WindowBuilder::new().build(&event_loop).unwrap();
// Create a proxy that can be used to send events to the event loop.
let proxy = event_loop.create_proxy();
// Block on the future indefinitely.
event_loop.block_on(
move |event, _, control_flow| {
match event {
Event::UserEvent(()) => control_flow.set_exit(),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id
} if window_id == window.id() => control_flow.set_exit(),
_ => {}
}
},
async move {
// Wait for one second.
async_io::Timer::after(Duration::from_secs(1)).await;
// Tell the event loop to close.
proxy.send_event(()).unwrap();
}
)
This is a contrived example, since control_flow.set_wait_deadline()
can do the same thing. See
the networking
example for a more complex and in-depth example of combining async
with winit
.
§Limitations
In both cases, the user event T
needs to be Send
and 'static
. This is because the event loop
proxy needs to be put into a Waker
. In addition, if you are not using run_return
, the future
needs to be 'static
. Both of these limitations could be removed if block_on
were integrated
directly into winit
.
Modules§
- prelude
- Import all relevant traits for this crate.
Structs§
- Signal
- The signal used to notify the event loop that it should wake up.
Enums§
- Block
OnReturn Result - Either one option or another.
Traits§
- Event
Loop Builder Ext - An extension trait for
EventLoopBuilder
that allows one to construct an event loop that can block on the future. - Event
Loop Ext - An extension trait for
EventLoop
that allows one to block on a future. - Event
Loop RunReturn Ext - An extension trait for
EventLoop
that allows one to block on a non-infinite future.