Last active
April 23, 2023 14:37
-
-
Save xavierarpa/9a98dcaf028905ae7ddd9ddc405dfdd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public sealed class BehaviorSubject<TValue> | |
{ | |
private TValue lastValue; | |
public Action<TValue> action = default; | |
public Action actionVoid = default; | |
public BehaviorSubject( TValue initValue = default ) | |
{ | |
lastValue = initValue; | |
} | |
public void Subscribe(bool condition, Action<TValue> callback) | |
{ | |
if (condition) callback.Invoke(lastValue); | |
SubscribeWithoutNotify(condition, callback); | |
} | |
public void SubscribeWithoutNotify(bool condition, Action<TValue> callback){ | |
if (condition) action += callback; | |
else action -= callback; | |
} | |
public void Subscribe_Void(bool condition, Action callback) | |
{ | |
if (condition) callback.Invoke(); | |
SubscribeWithoutNotify_Void(condition, callback); | |
} | |
public void SubscribeWithoutNotify_Void(bool condition, Action callback) | |
{ | |
if (condition) actionVoid += callback; | |
else actionVoid -= callback; | |
} | |
public void Invoke(TValue val) | |
{ | |
lastValue = val; | |
Invoke(); | |
} | |
public void Invoke() | |
{ | |
action?.Invoke(lastValue); | |
actionVoid?.Invoke(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment