我怎样才能看到我的被动扩展查询正在做什么?

我写了一个复杂的反应扩展查询与许多运营商。 我怎样才能看到发生了什么事?

我提出并回答这个问题,因为它出现得相当不错,可能是很好的一般用途。

您可以将这个function宽泛地添加到您的Rx操作员,而您正在开发它们以查看正在发生的事情:

public static IObservable<T> Spy<T>(this IObservable<T> source, string opName = null) { opName = opName ?? "IObservable"; Console.WriteLine("{0}: Observable obtained on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId); return Observable.Create<T>(obs => { Console.WriteLine("{0}: Subscribed to on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId); try { var subscription = source .Do(x => Console.WriteLine("{0}: OnNext({1}) on Thread: {2}", opName, x, Thread.CurrentThread.ManagedThreadId), ex => Console.WriteLine("{0}: OnError({1}) on Thread: {2}", opName, ex, Thread.CurrentThread.ManagedThreadId), () => Console.WriteLine("{0}: OnCompleted() on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId) ) .Subscribe(obs); return new CompositeDisposable( subscription, Disposable.Create(() => Console.WriteLine( "{0}: Cleaned up on Thread: {1}", opName, Thread.CurrentThread.ManagedThreadId))); } finally { Console.WriteLine("{0}: Subscription completed.", opName); } }); } 

下面是一个示例用法,显示了Range一个微妙的行为差异:

 Observable.Range(0, 1).Spy("Range").Subscribe(); 

给出输出:

 Range: Observable obtained on Thread: 7 Range: Subscribed to on Thread: 7 Range: Subscription completed. Range: OnNext(0) on Thread: 7 Range: OnCompleted() on Thread: 7 Range: Cleaned up on Thread: 7 

但是这个:

 Observable.Range(0, 1, Scheduler.Immediate).Spy("Range").Subscribe(); 

给出输出:

 Range: Observable obtained on Thread: 7 Range: Subscribed to on Thread: 7 Range: OnNext(0) on Thread: 7 Range: OnCompleted() on Thread: 7 Range: Subscription completed. Range: Cleaned up on Thread: 7 

指出不同?

显然,你可以改变这个写入日志或debugging,或使用预处理器指令来执行发布构build等精简传递订阅…

你可以在整个运营商链中应用Spy 。 例如:

 Observable.Range(0,3).Spy("Range") .Scan((acc, i) => acc + i).Spy("Scan").Subscribe(); 

给出输出:

 Range: Observable obtained on Thread: 7 Scan: Observable obtained on Thread: 7 Scan: Subscribed to on Thread: 7 Range: Subscribed to on Thread: 7 Range: Subscription completed. Scan: Subscription completed. Range: OnNext(1) on Thread: 7 Scan: OnNext(1) on Thread: 7 Range: OnNext(2) on Thread: 7 Scan: OnNext(3) on Thread: 7 Range: OnCompleted() on Thread: 7 Scan: OnCompleted() on Thread: 7 Range: Cleaned up on Thread: 7 Scan: Cleaned up on Thread: 7 

我相信你可以find丰富的方式来适应你的目的。