Skip to content

Instantly share code, notes, and snippets.

@loudej
Created January 9, 2011 08:31
Show Gist options
  • Save loudej/771534 to your computer and use it in GitHub Desktop.
Save loudej/771534 to your computer and use it in GitHub Desktop.
Making obs from stuff
public class Examples {
public void Foo() {
// these vars are all IObservable<string>
var src1 = Obs.Unit("one");
var src2 = Obs.Create(
new[] { "one", "two", "three" });
var src3 = Obs.Create<string>(write => {
write("one");
write("two");
write("three");
});
var src4 = Obs.Create(Bar());
}
IEnumerable<string> Bar() {
yield return "one";
yield return "two";
yield return "three";
}
}
public static class Obs {
public static IObservable<T> Create<T>(IEnumerable<T> enumerable) {
return new SyncObservable<T>(next => {
foreach (var item in enumerable) { next(item); }
});
}
public static IObservable<T> Create<T>(Action<Action<T>> produce) {
return new SyncObservable<T>(produce);
}
public static IObservable<T> Unit<T>(T value) {
return new SyncObservable<T>(next => next(value));
}
class SyncObservable<T> : IObservable<T> {
private readonly Action<Action<T>> _produce;
public SyncObservable(Action<Action<T>> produce) {
_produce = produce;
}
public IDisposable Subscribe(IObserver<T> observer) {
try {
_produce(observer.OnNext);
observer.OnCompleted();
}
catch (Exception ex) {
observer.OnError(ex);
}
return new Disposable();
}
}
class Disposable : IDisposable {
private readonly Action _dispose;
public Disposable() : this(() => { }) { }
public Disposable(Action dispose) { _dispose = dispose; }
public void Dispose() { _dispose(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment