-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIObservableExtensions.cs
248 lines (230 loc) · 9.43 KB
/
IObservableExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using ReactiveUI;
namespace RxCheatsheet
{
public static class IObservableExtensions
{
/// <summary>
/// Convenience method for Where(x => x != null).
/// </summary>
/// <remarks>
// Credit: Kent Boogaart
/// </remarks>
public static IObservable<T> WhereNotNull<T>(this IObservable<T> @this)
{
return @this.Where(x => x != null);
}
/// <summary>
/// Convenience method for Select(_ => Unit.Default).
/// </summary>
/// <remarks>
// Credit: Kent Boogaart
/// </remarks>
public static IObservable<Unit> ToSignal<T>(this IObservable<T> @this)
{
return @this.Select(_ => Unit.Default);
}
/// <summary>
/// Allows user to invoke actions upon subscription and disposal.
/// </summary>
/// <remarks>
// Credit: Kent Boogaart
// https://github.com/kentcb/YouIandReactiveUI
/// </remarks>
public static IObservable<T> DoLifetime<T>(this IObservable<T> @this, Action subscribed, Action unsubscribed)
{
return Observable
.Create<T>(
observer =>
{
subscribed();
var disposables = new CompositeDisposable();
@this
.Subscribe(observer)
.DisposeWith(disposables);
Disposable
.Create(() => unsubscribed())
.DisposeWith(disposables);
return disposables;
});
}
/// <summary>
/// Subscribes to the given observable and provides source code info about the caller when an
/// exception is thrown, without the user needing to supply an onError handler.
/// </summary>
/// <remarks>
// Credit: Kent Boogaart
// https://github.com/kentcb/YouIandReactiveUI
/// </remarks>
public static IDisposable SubscribeSafe<T>(
this IObservable<T> @this,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
return @this
.Subscribe(
_ => { },
ex =>
{
// Replace with your logger library.
Console.Error.WriteLine(
"An exception went unhandled: {0}" +
"Caller member name: {1}, " +
"caller file path: {2}, " +
"caller line number: {3}.",
ex,
callerMemberName,
callerFilePath,
callerLineNumber);
// Delete this line if you're not using ReactiveUI.
RxApp.DefaultExceptionHandler.OnNext(ex);
});
}
/// <summary>
/// Subscribes to the given observable and provides source code info about the caller when an
/// exception is thrown, without the user needing to supply an onError handler.
/// </summary>
/// <remarks>
// Credit: Kent Boogaart
// https://github.com/kentcb/YouIandReactiveUI
/// </remarks>
public static IDisposable SubscribeSafe<T>(
this IObservable<T> @this,
Action<T> onNext,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
return @this
.Subscribe(
onNext,
ex =>
{
// Replace with your logger library.
Console.Error.WriteLine(
"An exception went unhandled: {0}" +
"Caller member name: {1}, " +
"caller file path: {2}, " +
"caller line number: {3}.",
ex,
callerMemberName,
callerFilePath,
callerLineNumber);
// Delete this line if you're not using ReactiveUI.
RxApp.DefaultExceptionHandler.OnNext(ex);
});
}
/// <summary>
/// Allows the user to perform an action based on the current and previous emitted items.
/// </summary>
/// <remarks>
// Credit: James World
// http://www.zerobugbuild.com/?p=213
/// </remarks>
public static IObservable<T> WithPrevious<T>(this IObservable<T> @this, Func<T, T, T> projection)
{
return @this
.Scan(
Tuple.Create(default(T), default(T)),
(acc, current) => Tuple.Create(acc.Item2, current))
.Select(t => projection(t.Item1, t.Item2));
}
/// <summary>
/// Limits the rate at which events arrive from an Rx stream.
/// </summary>
/// <remarks>
// Credit: James World
// http://www.zerobugbuild.com/?p=323
/// </remarks>
public static IObservable<T> MaxRate<T>(this IObservable<T> @this, TimeSpan interval)
{
return @this
.Select(
x =>
{
return Observable
.Empty<T>()
.Delay(interval)
.StartWith(x);
})
.Concat();
}
/// <summary>
/// Like TakeWhile, except includes the emitted item that triggered the exit condition.
/// </summary>
/// <remarks>
/// Credit: Someone's answer on Stack Overflow
/// </remarks>
public static IObservable<T> TakeWhileInclusive<T>(this IObservable<T> @this, Func<T, bool> predicate)
{
return @this
.Publish(x => x.TakeWhile(predicate)
.Merge(x.SkipWhile(predicate).Take(1)));
}
/// <summary>
/// Buffers items in a stream until the provided predicate is true.
/// </summary>
/// <remarks>
/// Credit: Someone's answer on Stack Overflow
/// </remarks>
public static IObservable<IList<T>> BufferUntil<T>(this IObservable<T> @this, Func<T, bool> predicate)
{
var published = @this.Publish().RefCount();
return published.Buffer(() => published.Where(predicate));
}
/// <summary>
/// Prints a detailed log of what your Rx query is doing.
/// </summary>
/// <remarks>
// Credit: James World
// https://stackoverflow.com/questions/20220755/how-can-i-see-what-my-reactive-extensions-query-is-doing
/// </remarks>
public static IObservable<T> Spy<T>(this IObservable<T> @this, 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 = @this
.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);
}
});
}
/// <summary>
/// Prints the provided name next to stream emissions (useful for debugging).
/// </summary>
/// <remarks>
// Credit: Lee Campbell
// http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Aggregation
/// </remarks>
public static void Dump<T>(this IObservable<T> @this, string name)
{
@this.Subscribe(
i => Console.WriteLine("{0}-->{1}", name, i),
ex => Console.WriteLine("{0} failed-->{1}", name, ex.Message),
() => Console.WriteLine("{0} completed", name));
}
}
}