如果外部库只提供注册回调而不是事件,那么创建Observable
它的最佳方法是什么?
如果它是我可以使用的事件,Observable.FromEventPattern
但在这种情况下,我唯一的想法是Subject
在每个回调中使用a 和队列事件.
有没有更好的方法来做到这一点?
使用Observable.Create
.这是一个例子:
void Main() { var target = new SampleCallbacker(); var actionB = new Action(i => Console.WriteLine($"{i} * {i} = {i * i}.")); target.Register(actionB); var observable = Observable.Create (observer => { var action = new Action (i => observer.OnNext(i)); target.Register(action); return () => target.Unregister(action); }); var subscription = observable.Subscribe(i => Console.WriteLine($"From observable: {i} was fired.")); target.Fire(1); target.Fire(2); target.Fire(3); Console.WriteLine("Unsusbscribing observable..."); subscription.Dispose(); target.Fire(4); target.Fire(5); } class SampleCallbacker { private List > _actions = new List >(); public void Register(Action action) { _actions.Add(action); } public void Unregister(Action action) { while (_actions.Remove(action)) {} //loop remove } public void Fire(int i) { foreach (var action in _actions) { action(i); } } }