✨ promised fn
This commit is contained in:
parent
e3393f1e09
commit
0c190df5d7
4 changed files with 39 additions and 1 deletions
18
src/job.rs
18
src/job.rs
|
@ -7,6 +7,15 @@ pub struct JobDispatcher<T: Send + 'static, V: Send + 'static> {
|
|||
sender: Sender<JobOrder<T, V>>,
|
||||
}
|
||||
|
||||
pub struct JobResult<V>(std::sync::mpsc::Receiver<V>);
|
||||
|
||||
impl<V> JobResult<V> {
|
||||
/// Wait for the Result of a Job.
|
||||
pub fn wait(self) -> V {
|
||||
self.0.recv().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static, V: Send + 'static> JobDispatcher<T, V> {
|
||||
/// Creates a new instance of `JobDispatcher` and returns a tuple that contains it and a receiver end for `JobOrder`s.
|
||||
/// # Example:
|
||||
|
@ -48,6 +57,15 @@ impl<T: Send + 'static, V: Send + 'static> JobDispatcher<T, V> {
|
|||
rx.recv().unwrap()
|
||||
}
|
||||
|
||||
pub fn send_async(&self, param: T) -> JobResult<V> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let job_order = JobOrder::new(param, move |ret| {
|
||||
tx.send(ret).unwrap();
|
||||
});
|
||||
self.sender.send(job_order).unwrap();
|
||||
JobResult(rx)
|
||||
}
|
||||
|
||||
/// Sends a job of type `T` to the job dispatcher and waits for its result of type `V`.
|
||||
/// Returns `Some(V)` when the job returns an result, `None` if somehow nothing was returned or the internal `Mutex` is poisoned.
|
||||
pub fn try_send(&self, param: T) -> Option<V> {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue