Skip to main content

block_on_task

Function block_on_task 

Source
pub fn block_on_task<R, F>(task: F) -> R
where F: Future<Output = R> + Send + 'static, F::Output: Send + 'static,
Expand description

Given a closure task, push it onto the current tokio runtime for execution. Every [DEFAULT_SLEEP_DURATION] seconds, we check if the task has concluded. Once the task has concluded, we call tokio::block_on to resolve and extract the task result.

Because this helper function can fail, the return value is wrapped inside a RUMResult.

§Example

use rumtk_core::threading::threading_functions::{init_runtime, block_on_task};

const Hello: &str = "World!";

init_runtime(5);

let result = block_on_task(async {
    Hello
});

assert_eq!(Hello, result, "Result mismatches expected! {} vs. {}", Hello, result);

§Notes

    You need to wrap our call to block_on with a call to tokio::task::block_in_place to force
    cleanup of async executor and therefore avoid panics from the tokio runtime!
    Per Tokio's documentation, spawn_blocking would be better since it moves the task to an
    executor meant for blocking tasks instead of moving tasks out of the current thread and
    converting the thread into a clocking executor. The reason we don't do that is because
    the call to this function expects to block the current thread until completion and then
    return the result. If there's an issue with IO, revisit this function.

    https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html
    https://docs.rs/tokio/latest/tokio/runtime/struct.Runtime.html#method.block_on
    https://docs.rs/tokio/latest/tokio/runtime/struct.Handle.html#method.spawn_blocking
    https://docs.rs/tokio/latest/tokio/runtime/struct.Handle.html#method.spawn_blocking