Saturday, 9 January 2010

Weak Subscribe to an IObservable Source

namespace Reactive
module Extensions =

    open System
    open System.Runtime.CompilerServices

    type IObserver<'a> =
        abstract member OnNext : 'a -> unit

    type IObservable<'a> =
        abstract member Subscribe : IObserver<'a> -> IDisposable

    let Subscribe<'a> (o:IObservable<'a>, f) =
        o.Subscribe({ new IObserver<'a> with
                          member this.OnNext x = f x })

    let SubscribeWeakly<'a> (o:IObservable<'a>, a:Action<'a>) =
        let (m, r) = (a.Method, new WeakReference(a.Target))
        let rec disposable = Subscribe(o, fun x -> if (r.IsAlive) then
                                                      ignore (m.Invoke (r.Target, [|x|]))
                                                      disposable.Dispose ())