Move tester to a new iced_tester subcrate

This commit is contained in:
Héctor Ramón Jiménez 2025-08-29 08:39:44 +02:00
parent 9e81c2b9e8
commit 4f7444bddf
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
28 changed files with 392 additions and 355 deletions

View file

@ -9,6 +9,7 @@ use crate::futures::{BoxStream, MaybeSend, boxed_stream};
use std::convert::Infallible;
use std::sync::Arc;
use std::thread;
#[cfg(feature = "sipper")]
#[doc(no_inline)]
@ -466,3 +467,47 @@ pub fn effect<T>(action: impl Into<Action<Infallible>>) -> Task<T> {
pub fn into_stream<T>(task: Task<T>) -> Option<BoxStream<Action<T>>> {
task.stream
}
/// Creates a new [`Task`] that will run the given closure in a new thread.
///
/// Any data sent by the closure through the [`mpsc::Sender`] will be produced
/// by the [`Task`].
pub fn blocking<T>(f: impl FnOnce(mpsc::Sender<T>) + Send + 'static) -> Task<T>
where
T: Send + 'static,
{
let (sender, receiver) = mpsc::channel(1);
let _ = thread::spawn(move || {
f(sender);
});
Task::stream(receiver)
}
/// Creates a new [`Task`] that will run the given closure that can fail in a new
/// thread.
///
/// Any data sent by the closure through the [`mpsc::Sender`] will be produced
/// by the [`Task`].
pub fn try_blocking<T, E>(
f: impl FnOnce(mpsc::Sender<T>) -> Result<(), E> + Send + 'static,
) -> Task<Result<T, E>>
where
T: Send + 'static,
E: Send + 'static,
{
let (sender, receiver) = mpsc::channel(1);
let (error_sender, error_receiver) = oneshot::channel();
let _ = thread::spawn(move || {
if let Err(error) = f(sender) {
let _ = error_sender.send(Err(error));
}
});
Task::stream(stream::select(
receiver.map(Ok),
stream::once(error_receiver).filter_map(async |result| result.ok()),
))
}