Skip to content

Commit

Permalink
Add Bastion::spawn method to create a child with the action without u…
Browse files Browse the repository at this point in the history
…sing Children::with_exec
  • Loading branch information
Stupremee committed Dec 11, 2019
1 parent e35c485 commit 693c8d4
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions bastion/src/bastion.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::broadcast::{Broadcast, Parent};
use crate::children::{Children, ChildrenRef};
use crate::config::Config;
use crate::context::BastionContext;
use crate::message::{BastionMessage, Message};
use crate::supervisor::{Supervisor, SupervisorRef};
use crate::system::SYSTEM;
use core::future::Future;
use std::fmt::{self, Debug, Formatter};
use std::thread;

Expand Down Expand Up @@ -328,6 +330,51 @@ impl Bastion {
SYSTEM.supervisor().children(init)
}

/// Creates a new [`Children`] which will have the given closure
/// as action and then sends it to the system's default supervisor.
///
/// This method returns a [`ChildrenRef`] referencing the newly created children
/// if the creation was successful, otherwise returns an `Err(())`.
///
/// Internally this method uses the [`Bastion::children`] and [`Children::with_exec`] methods
/// to create a new children.
///
/// # Arguments
/// * `action` - The closure which gets executed by the child.
///
/// # Example
///
/// ```rust
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// let children_ref: ChildrenRef = Bastion::spawn(|ctx: BastionContext| {
/// async move {
/// // ...
/// Ok(())
/// }
/// }).expect("Couldn't create the children group.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Children::with_exec`]: children/struct.Children.html#method.with_exec
/// [`Bastion::children`]: #method.children
/// [`Children`]: children/struct.Children.html
/// [`ChildrenRef`]: children/struct.ChildrenRef.html
pub fn spawn<I, F>(action: I) -> Result<ChildrenRef, ()>
where
I: Fn(BastionContext) -> F + Send + Sync + 'static,
F: Future<Output = Result<(), ()>> + Send + 'static,
{
Bastion::children(|ch| ch.with_exec(action))
}

/// Sends a message to the system which will then send it to all
/// the root-level supervisors and their supervised children and
/// supervisors, etc.
Expand Down

0 comments on commit 693c8d4

Please sign in to comment.