Created
April 30, 2013 06:41
-
-
Save markusjohnsson/5486979 to your computer and use it in GitHub Desktop.
Creates an observable that, when subscribed to, will subscribe to the underlying observable, but will not dispose that subscription when its own subscription is disposed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reactive; | |
using System.Reactive.Linq; | |
namespace RxFireAndForget | |
{ | |
public static class RxExtensions | |
{ | |
/// <summary> | |
/// Creates an observable that, when subscribed to, will subscribe to the underlying observable, | |
/// but will not dispose that subscription when its own subscription is disposed. | |
/// </summary> | |
public static IObservable<T> FireAndForget<T>(this IObservable<T> source) | |
{ | |
return Observable | |
.Create( | |
(IObserver<T> outerObserver) => | |
{ | |
var alive = true; | |
var innerObserver = Observer | |
.Create<T>( | |
n => | |
{ | |
if (alive) | |
outerObserver.OnNext(n); | |
}, | |
e => | |
{ | |
if (alive) | |
outerObserver.OnError(e); | |
}, | |
() => | |
{ | |
if (alive) | |
outerObserver.OnCompleted(); | |
}); | |
// FIRE! | |
var disposable = source | |
.Subscribe(innerObserver); | |
return () => | |
{ | |
// STOP PROPAGATING EVENTS | |
alive = false; | |
// BUT FORGET TO DISPOSE | |
}; | |
}); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment