pub struct Task<'a, T = (), E = ()> { /* private fields */ }
Expand description
Tasks can be used to execute code in Task Kit’s runner thread pool. This is the key primive of this crate. It can be used to build and organize asyncronous code paths.
For more on how to use tasks see the crate documentation.
#Examples
Polling example:
let mut i = 0;
let task: Task<u32, ()> = Task::new(move || {
if i < 100 {
i += 1;
Pending
} else {
Resolve(i)
}
});
Long running example:
let task: Task<u32, ()> = Task::with(move || {
let mut i = 0;
while i < 100 {
i += 1;
}
i
});
Implementations§
Source§impl<'a, T, E> Task<'a, T, E>where
T: 'a,
E: 'a,
impl<'a, T, E> Task<'a, T, E>where
T: 'a,
E: 'a,
Sourcepub fn new<F>(task: F) -> Self
pub fn new<F>(task: F) -> Self
Create a new task from a closure returning a State
Provide the new function a closure that contains the logic you wish
to execute asyncronously. This closure will be executed upon the thread
pool within the runner until your closure returns an instance of
State::Resolve
containing a value or an instance of State::Reject
containing an error value.
§Arguments
task
- A closure containing code to be executed asyncronously by the runner.
§Examples
let task: Task<String, ()> = Task::new(|| Resolve(do_something_blocking()));
Sourcepub fn with<F>(with: F) -> Selfwhere
F: FnMut() -> T + 'a,
pub fn with<F>(with: F) -> Selfwhere
F: FnMut() -> T + 'a,
Create a new task from a closure returning a value.
The closure will only be executed once by the runner, and is expected to return the value you wish to resolve.
§Arguments
with
- A closure that will return the value you’d like the task to resolve.
§Examples
let task: Task<String, ()> = Task::with(|| do_something_blocking());
Sourcepub fn join<U>(self, task: Task<'a, U, E>) -> Task<'a, (T, U), E>where
U: 'a,
pub fn join<U>(self, task: Task<'a, U, E>) -> Task<'a, (T, U), E>where
U: 'a,
Create a new merged task from the current task instance and a second task
Join will return a new task that will resolve a tuple containing the
results from both the task join
is called upon, and the task passed in.
Both the current task and the second task passed in will still execute in parallel.
§Arguments
task
- A second task to join with the current task
§Examples
let merged_task = my_task.join(my_other_task);
Sourcepub fn state(&self) -> &State<T, E>
pub fn state(&self) -> &State<T, E>
Get the task state
Returns a reference to the internal state of the task
Sourcepub fn poll(&mut self) -> Option<Result<T, E>>
pub fn poll(&mut self) -> Option<Result<T, E>>
Executes the closure within the task once
If the task resolves or rejects then the returned option will contain a result object.
Sourcepub fn wait(self) -> Option<Result<T, E>>
pub fn wait(self) -> Option<Result<T, E>>
Executes the closure within the task blocking until the task completes