我是RX的新手,玩了一些样本,关于控制台的原因有什么想法吗?订阅中的writeLine没有被调用?
如果我去掉var obs = Observable。创建(i =>{
while(true) { Thread.Sleep(250); i.OnNext(2.0); } return () => { }; }) .SubscribeOn(Scheduler.TaskPool) .ObserveOn(Scheduler.CurrentThread) .Subscribe(i => { Console.WriteLine("Inside Subscribe"); });
.ObserveOn(Scheduler.CurrentThread)
line all is fine?
谢谢
正如我提到的,SubscribeOn
和ObserveOn
不是最好命名的方法;我强烈建议你从头到尾读一遍:
基本上,SubscribeOn
告诉系统在什么上下文中执行实际的订阅/取消订阅连接,而ObserveOn
告诉系统在新值到达源时"执行"什么上下文中。
首先,请允许我稍微调整一下您的示例:
Console.WriteLine("Start Thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
var subscription = Observable.Create<double>(i =>
{
Console.WriteLine("Observable thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
while(true)
{
Console.WriteLine("Pushing values from thread {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(250);
i.OnNext(2.0);
}
return () => { };
})
.SubscribeOn(Scheduler.TaskPool)
.ObserveOn(Scheduler.CurrentThread)
.Subscribe(i =>
{
Console.WriteLine("Subscribable thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Inside Subscribe");
});
Console.ReadLine();
subscription.Dispose();
如果你运行这个命令,你会看到如下内容:
Start Thread ID:21
Observable thread ID:23
Pushing values from thread 23
Pushing values from thread 23
Pushing values from thread 23
Pushing values from thread 23
现在让我们交换ObserveOn
和SubscribeOn
的线程:
.SubscribeOn(Scheduler.CurrentThread)
.ObserveOn(Scheduler.TaskPool)
现在我们得到:
Start Thread ID:26
Observable thread ID:26
Pushing values from thread 26
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe