I\'m writing a complex Reactive Extensions query with lots of operators. How can I see what\'s going on?
I\'m asking and answering this as it comes up a fair bit and
Another three years have passed, and I'm still using your idea. My version has now evolved as follows:
The code:
public static IObservable Spy(this IObservable source, string opName = null)
{
return Spy(source, opName, Console.WriteLine);
}
public static IObservable Spy(this IObservable source, string opName,
Action logger)
{
opName = opName ?? "IObservable";
logger($"{opName}: Observable obtained on Thread: {Thread.CurrentThread.ManagedThreadId}");
var count = 0;
return Observable.Create(obs =>
{
logger($"{opName}: Subscribed to on Thread: {Thread.CurrentThread.ManagedThreadId}");
try
{
var subscription = source
.Do(x => logger($"{opName}: OnNext({x}) on Thread: {Thread.CurrentThread.ManagedThreadId}"),
ex => logger($"{opName}: OnError({ex}) on Thread: {Thread.CurrentThread.ManagedThreadId}"),
() => logger($"{opName}: OnCompleted() on Thread: {Thread.CurrentThread.ManagedThreadId}")
)
.Subscribe(t =>
{
try
{
obs.OnNext(t);
}
catch(Exception ex)
{
logger($"{opName}: Downstream exception ({ex}) on Thread: {Thread.CurrentThread.ManagedThreadId}");
throw;
}
}, obs.OnError, obs.OnCompleted);
return new CompositeDisposable(
Disposable.Create(() => logger($"{opName}: Dispose (Unsubscribe or Observable finished) on Thread: {Thread.CurrentThread.ManagedThreadId}")),
subscription,
Disposable.Create(() => Interlocked.Decrement(ref count)),
Disposable.Create(() => logger($"{opName}: Dispose (Unsubscribe or Observable finished) completed, {count} subscriptions"))
);
}
finally
{
Interlocked.Increment(ref count);
logger($"{opName}: Subscription completed, {count} subscriptions.");
}
});
}