3 unstable releases
0.2.1 | Nov 12, 2023 |
---|---|
0.2.0 | Feb 7, 2023 |
0.1.0 | Feb 7, 2023 |
#54 in #event
320KB
174 lines
winit-block-on
Use winit
to block on futures. This enables winit
to be seamlessly integrated into the async
ecosystem.
License
This package is dual licensed under the Boost Software License version 1.0 or the Apache License version 2.0.
Roboto Regular is licensed under the Open Font License.
lib.rs
:
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
.
Dependencies
~2–15MB
~144K SLoC