reactive messenger, event bus, observer pattern
This is a simple library that helps you send data between modules that you want to keep independent. The library also includes a logger to help you debug signals.
I personally recommend using it between gameplay modules, services, and UI modules. However, it is possible to overuse it, which can decrease the readability of the code in the project and create difficulties with debugging.
Add the git url in the unity package manager:
https://github.com/AlehZakharau/ReactiveMessenger.git?path=/Assets/ReactiveSystem
or Add the line below in the manifest
"com.alehzakharau.reactivesystem": "https://github.com/AlehZakharau/ReactiveMessenger.git?path=/Assets/ReactiveSystem",
To learn more, check the samples in the package.
You can use the EventBus like a singleton or create an instance and register it in dependency injection.
public struct MessageSignal
{
public float Value;
public string Message;
public MessageSignal(string message, float value)
{
Message = message;
Value = value;
}
}
{
EventBus.Instance.Subscribe<MessageSignal>(obj => Debug.Log(obj.Message));
// or
EventBus.Instance.Subscribe<MessageSignal>(OnMessageArrived);
}
private void OnMessageArrived(MessageSignal obj)
{
Debug.Log(obj.Message);
Debug.Log(obj.Value);
}
private void Start()
{
EventBus.Instance.Fire(new MessageSignal("Hello world", 2));
}
If you no longer want to receive messages, you can unsubscribe.
{
EventBus.Instance.UnSubscribe<MessageSignal>(OnMessageArrived);
}
Press "Tools/EventBusLogActivator" to activate the logger. The logger will send messages about Fire, Subscribe, and Unsubscribe to the console.
I insist on not using it in an update loop.
MIT License