From 612528904034a23f1b5f5fefc59fb97294e39654 Mon Sep 17 00:00:00 2001 From: Anton Tarasenko Date: Sat, 18 Jul 2020 02:21:23 +0700 Subject: [PATCH] Add events ability to start/shutdown `Service` Events might rely on a particular `Service` to generate them, this patch allows them to auto-launch/shutdown a service, depending on whether anybody is listening to it's events. --- sources/Core/Events/Events.uc | 36 ++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/sources/Core/Events/Events.uc b/sources/Core/Events/Events.uc index 86cf877..4f6a0a0 100644 --- a/sources/Core/Events/Events.uc +++ b/sources/Core/Events/Events.uc @@ -70,6 +70,13 @@ var private array< class > listeners; var public const class relatedListener; +// Even class can also auto-spawn a `Service`, +// in case it's require to generate events +var public const class connectedServiceClass; +// Set this to `true`if you want `connectedServiceClass` service to also +// auto-shutdown whenever no-one listens to the events. +var public const bool shutDownServiceWithoutListeners; + static public final function array< class > GetListeners() { return default.listeners; @@ -83,10 +90,15 @@ static public final function bool ActivateListener(class newListener) if (newListener == none) return false; if (!ClassIsChildOf(newListener, default.relatedListener)) return false; + // Spawn service, if absent + if ( default.listeners.length == 0 + && default.connectedServiceClass != none) { + default.connectedServiceClass.static.Require(); + } + // Add listener for (i = 0;i < default.listeners.length;i += 1) { - if (default.listeners[i] == newListener) - { + if (default.listeners[i] == newListener) { return false; } } @@ -99,17 +111,31 @@ static public final function bool ActivateListener(class newListener) static public final function bool DeactivateListener(class listener) { local int i; + local bool removedListener; + local Service service; if (listener == none) return false; - + + // Remove listener for (i = 0; i < default.listeners.length; i += 1) { if (default.listeners[i] == listener) { default.listeners.Remove(i, 1); - return true; + removedListener = true; + break; } } - return false; + // Remove unneeded service + if ( default.shutDownServiceWithoutListeners + && default.listeners.length == 0 + && default.connectedServiceClass != none) + { + service = Service(default.connectedServiceClass.static.GetInstance()); + if (service != none) { + service.Destroy(); + } + } + return removedListener; } static public final function bool IsActiveListener(class listener)