Skip to content

Instantly share code, notes, and snippets.

@markusjohnsson
Created April 30, 2013 06:41
Show Gist options
  • Save markusjohnsson/5486979 to your computer and use it in GitHub Desktop.
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.
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