Search code examples
f#observablereactive-programmingsystem.reactiverx.net

Observable from callback method


Let say I have a class which iherits legacy API and overrides a virtual method which is called when something happens

type MyClass() as this =
    let somethingObservable: IObservable<Something> = ...

    override _.OnSomething(s: Something) = ...

How can I translate each invokation of OnSomething to a notification of somethingObservable?

That's probably a simple question, but I could not find a way to do it properly (should I use not advised ISubject?). Appreciate your help.


Solution

  • Using a subject like this is fine, and ensures correctness in the implementation. Here's an example using FSharp.Control.Reactive, which gets you the idiomatic way of writing this.

    type MyClass() =
        inherit Legacy()
        let somethingObservable = 
            Subject.broadcast
    
        override _.OnSomething s = 
            somethingObservable |> Subject.onNext s |> ignore
    
        member _.AsObservable = 
            somethingObservable |> Observable.asObservable
    

    You can also use new Subject<_> and its methods, same thing. In some assembly if you'd prefer not to take on the System.Reactive dependency, F# also natively supports IObservable through events.

    type MyClassEvt() =
        inherit Legacy()
        let event = new Event<_>()
    
        override _.OnSomething s = 
            event.Trigger s
    
        member _.AsObservable = 
            event.Publish :> IObservable<_>