D4rWiNS
D4rWiNS

Reputation: 2615

How to consume System.Action after use

I am using delegates to communicate between my classes like this

 public event System.Action OnAdFinishedOk;

however, every time I subscribe to this event, after use it, I need to remove like this adsManager.OnAdFinishedOk -= Revivir;

I can introduce bugs if I forget to unsubscribe from the delegate,

Is any way to make a subscription to a delegate and consume the subscription after the use, so I don't need to unsubscribe? (I am open to another approach)

Upvotes: 1

Views: 85

Answers (1)

dcg
dcg

Reputation: 4219

I had similar situation and I solve it like:

public void Register(Action action) {
    Action _action = null;
    _action = ()=> {
        action();
        OnAdFinishedOk -= _action;
    }
    OnAdFinishedOk += _action;
}

Hope it helps!

Upvotes: 2

Related Questions