Skip to content

Instantly share code, notes, and snippets.

@benoitjadinon
Last active November 12, 2016 23:02
Show Gist options
  • Select an option

  • Save benoitjadinon/0bc993039f65b21b76f48f8a7a9d11f2 to your computer and use it in GitHub Desktop.

Select an option

Save benoitjadinon/0bc993039f65b21b76f48f8a7a9d11f2 to your computer and use it in GitHub Desktop.
public static class RxExtensions
{
/*
.TraceWithName(nameof(Reachability))
> Rx Reachability#1: Subscribe()
> Rx Reachability#1: OnNext(False)
.TraceWithName(nameof(reach.WhenConnectedChanged), this)
> Rx AppDelegate_WhenConnectedChanged:2037545460#1: Subscribe()
> Rx AppDelegate_WhenConnectedChanged:2037545460#1: OnNext(connected)
*/
public static IObservable<TSource> Trace<TSource>(this IObservable<TSource> source, object @class)
{
return Trace(source, @class.GetType().Name, @class.GetHashCode().ToString());
}
public static IObservable<TSource> TraceWithName<TSource>(this IObservable<TSource> source, string name)
{
return Trace(source, $"{name}");
}
public static IObservable<TSource> TraceWithName<TSource>(this IObservable<TSource> source, string name, object @class)
{
return Trace(source, $"{@class.GetType().Name}_{name}", @class.GetHashCode().ToString());
}
// http://www.lavinski.me/debugging-rx-with-seq/
private static IObservable<TSource> Trace<TSource>(this IObservable<TSource> source, string name, string hash = null)
{
var id = 0;
return Observable.Create<TSource>(observer =>
{
var itemId = ++id;
Action<string, object> trace =
(method, value) => Debug.WriteLine(
$"Rx {name}{(hash != null ? ":" + hash : "")}#{itemId}: {method}({value})"
);
trace("Subscribe", null);
var disposable = source.Subscribe(
onNext: v => { trace("OnNext", v); observer.OnNext(v); },
onError: e => { trace("OnError", e); observer.OnError(e); },
onCompleted: () => { trace("OnCompleted", null); observer.OnCompleted(); });
return
() => { trace("Dispose", null); disposable.Dispose(); };
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment