如何开始评估冷 IObservable
How to start evaluating a cold IObservable
我想,冷 IObservables,就像从 Observable.Create
返回的那样,只要订阅它们就会被评估。我订阅了。 IObservable 没有评估。
class Program
{
static IObservable<int> HotSource()
{
return Observable.Generate<int, int>(0, x => x <= 100, x => x + 1, x => x);
}
static IObservable<int> ColdSource()
{
return Observable.Create<int>(subscriber => () =>
{
for (int i = 0; i <= 100; ++i)
{
subscriber.OnNext(i);
}
});
}
static void Process(IObservable<int> numbers)
{
numbers
.Take(15)
.Subscribe(Console.WriteLine);
}
static void Main(string[] args)
{
Console.WriteLine("Hot");
Process(HotSource());
Console.WriteLine("Cold");
Process(ColdSource());
Console.WriteLine("End");
Console.ReadLine();
}
}
您的创建方法已关闭。这将起作用:
static IObservable<int> ColdSource()
{
return Observable.Create<int>(subscriber =>
{
for (int i = 0; i <= 100; ++i)
{
subscriber.OnNext(i);
}
subscriber.OnCompleted();
return Disposable.Empty;
});
}
按照你写的方式,你返回了一个 Action
,它发生在 un-subscription 上。您希望代码在订阅时发生。
顺便说一句,您的 'Hot' observable 不是很热。我不知道这对你是否有影响。您可以在这段代码中看到:
static void Main(string[] args)
{
Console.WriteLine("Hot 1");
var hotSource = HotSource();
Process(hotSource);
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("Hot 2");
Process(hotSource);
Console.ReadLine();
}
如果hotSource
真的很热,每个数字只会打印一次,或者它们会同时打印(1、1、2、2,等等)。
我想,冷 IObservables,就像从 Observable.Create
返回的那样,只要订阅它们就会被评估。我订阅了。 IObservable 没有评估。
class Program
{
static IObservable<int> HotSource()
{
return Observable.Generate<int, int>(0, x => x <= 100, x => x + 1, x => x);
}
static IObservable<int> ColdSource()
{
return Observable.Create<int>(subscriber => () =>
{
for (int i = 0; i <= 100; ++i)
{
subscriber.OnNext(i);
}
});
}
static void Process(IObservable<int> numbers)
{
numbers
.Take(15)
.Subscribe(Console.WriteLine);
}
static void Main(string[] args)
{
Console.WriteLine("Hot");
Process(HotSource());
Console.WriteLine("Cold");
Process(ColdSource());
Console.WriteLine("End");
Console.ReadLine();
}
}
您的创建方法已关闭。这将起作用:
static IObservable<int> ColdSource()
{
return Observable.Create<int>(subscriber =>
{
for (int i = 0; i <= 100; ++i)
{
subscriber.OnNext(i);
}
subscriber.OnCompleted();
return Disposable.Empty;
});
}
按照你写的方式,你返回了一个 Action
,它发生在 un-subscription 上。您希望代码在订阅时发生。
顺便说一句,您的 'Hot' observable 不是很热。我不知道这对你是否有影响。您可以在这段代码中看到:
static void Main(string[] args)
{
Console.WriteLine("Hot 1");
var hotSource = HotSource();
Process(hotSource);
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("Hot 2");
Process(hotSource);
Console.ReadLine();
}
如果hotSource
真的很热,每个数字只会打印一次,或者它们会同时打印(1、1、2、2,等等)。