以下将无法捕获发射的值:
someObservable = Observable.FromEventPattern(this, "MyEvent");
FireMyEvent("foo");
await someObservable.FirstOrDefaultAsync(e => e.Args == "foo");
所以我在单元测试中遇到了这种模式:
var tsc = new TaskCompletionSource<bool>();
var callback = someObservable.FirstOrDefaultAsync(...);
using (callback.Subscribe(e => tsc.SetResult(e.Args)))
{
FireMyEvent("foo");
tsc.Task.Wait(1000);
}
Assert.AreEqual("foo", tsc.Task.Result);
基本上,我需要订阅,然后触发操作,然后等待订阅的可观察对象。
是否可以在不引入新Task或WaitHandle的情况下简化此订阅/等待?
答案 0 :(得分:0)
我不确定您到底想做什么,但是如果我了解基本思想,那么就可以了:
var subject = new Subject<Unit>();
var callback = subject.FirstOrDefaultAsync();
using (callback.Subscribe(_ => { }, () => Console.WriteLine("Done.")))
{
subject.OnNext(Unit.Default);
}
您能更全面地解释用例吗?
答案 1 :(得分:0)
someObservable = Observable.FromEventPattern(this, "MyEvent");
Task.Delay(1000).ContinueWith(_ => FireMyEvent("foo"));
var result = await someObservable.FirstOrDefaultAsync(e => e.Args == "foo");
您的结果现在是一个EventPattern。但是,我建议使用更安全的FromEventPattern-Overload类型:
var eventObservable = Observable
.FromEventPattern<YourEventArgs>(
h => MyEvent += h,
h => MyEvent -= h);