反应程序在等待后不会终止
Reactive program doesn't terminate after wait
我希望下面的程序在您点击 z
之前回显任何按键,但是当您点击 z
时它不会终止,并且只会回显每隔一个按键。我做错了什么?
using System.Reactive;
using System.Reactive.Linq;
public class Printer : IObserver<char>
{
public void OnNext(char x)
{
Console.WriteLine(x);
}
public void OnError(Exception x)
{
}
public void OnCompleted()
{
}
}
class Program
{
static IObservable<char> keys = Observable.Defer(() =>Observable.Start(() =>Console.ReadKey().KeyChar)).Repeat(); //
public static int Main()
{
IObserver<char> x = new Printer();
keys.Subscribe(x);
keys.Where(b => b == 'z').Wait();
return 0;
}
}
好的,所以有两个问题,都是分开的:
你这里有一个 cold observable。
只有当你开始观察它时,它才会产生价值。
相反,每次您订阅它时,它都代表一个新的流 - 类似于 IEnumerable
每次尝试获取项目时的评估方式。如果在 Observable.Defer
中放置一个断点,您可以清楚地看到这一点。
您可以拥有这两个流 share just one subscription to the source,即可观察到的按键。所以我们将冷的可观察到的转化为热的。
Wait
方法是:
Waits for the observable sequence to complete and returns the last element of
the sequence. If the sequence terminates with an OnError notification, the exception
is thrown.
所以它将等到序列完成,即 OnCompleted
已在可观察链中被调用。因此,我们使用 TakeUntil
以便序列仅在满足条件时完成(按 'z')。
public static int Main()
{
var keys_stream = keys.Publish().RefCount(); // share
IObserver<char> x = new Printer();
keys_stream.Subscribe(x);
keys_stream.TakeUntil(b => b == 'z').Wait(); //wait until z
return 0;
}
我希望下面的程序在您点击 z
之前回显任何按键,但是当您点击 z
时它不会终止,并且只会回显每隔一个按键。我做错了什么?
using System.Reactive;
using System.Reactive.Linq;
public class Printer : IObserver<char>
{
public void OnNext(char x)
{
Console.WriteLine(x);
}
public void OnError(Exception x)
{
}
public void OnCompleted()
{
}
}
class Program
{
static IObservable<char> keys = Observable.Defer(() =>Observable.Start(() =>Console.ReadKey().KeyChar)).Repeat(); //
public static int Main()
{
IObserver<char> x = new Printer();
keys.Subscribe(x);
keys.Where(b => b == 'z').Wait();
return 0;
}
}
好的,所以有两个问题,都是分开的:
你这里有一个 cold observable。 只有当你开始观察它时,它才会产生价值。 相反,每次您订阅它时,它都代表一个新的流 - 类似于
IEnumerable
每次尝试获取项目时的评估方式。如果在Observable.Defer
中放置一个断点,您可以清楚地看到这一点。您可以拥有这两个流 share just one subscription to the source,即可观察到的按键。所以我们将冷的可观察到的转化为热的。
Wait
方法是:Waits for the observable sequence to complete and returns the last element of the sequence. If the sequence terminates with an OnError notification, the exception is thrown.
所以它将等到序列完成,即
OnCompleted
已在可观察链中被调用。因此,我们使用TakeUntil
以便序列仅在满足条件时完成(按 'z')。public static int Main() { var keys_stream = keys.Publish().RefCount(); // share IObserver<char> x = new Printer(); keys_stream.Subscribe(x); keys_stream.TakeUntil(b => b == 'z').Wait(); //wait until z return 0; }