Add SustemRunner::with_block_on() helper, allows to use custom block_on fn

This commit is contained in:
Nikolay Kim 2024-08-31 12:32:10 +05:00
parent d87d9b2139
commit d2bbe9e48e
3 changed files with 33 additions and 2 deletions

View file

@ -1,5 +1,9 @@
# Changes
## [0.4.16] - 2024-08-31
* Add SustemRunner::with_block_on() helper, allows to use custom block_on fn
## [0.4.15] - 2024-08-30
* No runtime compatibility

View file

@ -1,6 +1,6 @@
[package]
name = "ntex-rt"
version = "0.4.15"
version = "0.4.16"
authors = ["ntex contributors <team@ntex.rs>"]
description = "ntex runtime"
keywords = ["network", "framework", "async", "futures"]

View file

@ -1,5 +1,5 @@
#![allow(clippy::let_underscore_future)]
use std::{cell::RefCell, future::Future, io, rc::Rc};
use std::{cell::RefCell, future::Future, io, pin::Pin, rc::Rc};
use async_channel::unbounded;
@ -136,6 +136,33 @@ impl SystemRunner {
}
}
/// Execute a future with custom `block_on` method and wait for result.
#[inline]
pub fn with_block_on<B, F, R>(self, block_on: B, fut: F) -> R
where
B: FnOnce(Pin<Box<dyn Future<Output = ()>>>),
F: Future<Output = R> + 'static,
R: 'static,
{
let SystemRunner {
arb,
arb_controller,
..
} = self;
// run loop
let result = Rc::new(RefCell::new(None));
let result_inner = result.clone();
block_on(Box::pin(async move {
let _ = crate::spawn(arb);
let _ = crate::spawn(arb_controller);
let r = fut.await;
*result_inner.borrow_mut() = Some(r);
}));
let res = result.borrow_mut().take().unwrap();
res
}
#[cfg(feature = "tokio")]
/// Execute a future and wait for result.
pub async fn run_local<F, R>(self, fut: F) -> R