diff --git a/actix-rt/CHANGES.md b/actix-rt/CHANGES.md index 74e94aed..72c450c6 100644 --- a/actix-rt/CHANGES.md +++ b/actix-rt/CHANGES.md @@ -2,8 +2,10 @@ ## Unreleased - 2021-xx-xx * Add `Arbiter::handle` to get a handle of an owned Arbiter. [#274] +* Add `System::try_current` for situations where actix may or may not be running a System. [#275] [#274]: https://github.com/actix/actix-net/pull/274 +[#275]: https://github.com/actix/actix-net/pull/275 ## 2.0.1 - 2021-02-06 diff --git a/actix-rt/src/system.rs b/actix-rt/src/system.rs index b7f134cb..3bc8a6e3 100644 --- a/actix-rt/src/system.rs +++ b/actix-rt/src/system.rs @@ -100,6 +100,15 @@ impl System { }) } + /// Try to get current running system. + /// + /// Returns `None` if no System has been started. + /// + /// Contrary to `current`, this never panics. + pub fn try_current() -> Option { + CURRENT.with(|cell| cell.borrow().clone()) + } + /// Get handle to a the System's initial [Arbiter]. pub fn arbiter(&self) -> &ArbiterHandle { &self.arbiter_handle diff --git a/actix-rt/tests/tests.rs b/actix-rt/tests/tests.rs index 5a292b31..86fba96d 100644 --- a/actix-rt/tests/tests.rs +++ b/actix-rt/tests/tests.rs @@ -288,3 +288,13 @@ fn new_arbiter_with_tokio() { assert_eq!(false, counter.load(Ordering::SeqCst)); } + +#[test] +fn try_current_no_system() { + assert!(System::try_current().is_none()) +} + +#[test] +fn try_current_with_system() { + System::new().block_on(async { assert!(System::try_current().is_some()) }); +}