有人能帮我实现对 IObserver 的同步订阅吗?这样调用方法将会在订阅完成前一直阻塞。
示例:
发布者
public static class Publisher {
public static IObservable<string> NonBlocking()
{
return Observable.Create<string>(
observable =>
{
Task.Run(() =>
{
observable.OnNext("a");
Thread.Sleep(1000);
observable.OnNext("b");
Thread.Sleep(1000);
observable.OnCompleted();
Thread.Sleep(1000);
});
return Disposable.Create(() => Console.WriteLine("Observer has unsubscribed"));
});
}
}
Subscriber
public static class Subscriber{
public static bool Subscribe()
{
Publisher.NonBlocking().Subscribe((s) =>
{
Debug.WriteLine(s);
}, () =>
{
Debug.WriteLine("Complete");
});
// This will currently return true before the subscription is complete
// I want to block and not Return until the Subscriber is Complete
return true;
}
}
await
关键字等待一个IObservable<>
。它将返回序列中的最后一项。 - Cory Nelson