Search code examples
f#observablereactive-programming

Combine Observables


Let say I have

A: IObservable<int> 
B: IObservable<int> 

how can I combine these two into

C: IObservable<int> 

which emitted value is a product of last observed values of A and B?

E.g.

A = [ 2   3       1 ]
B = [   2   5  6    ]

then

C = [   4 6 15 18 6 ] 

Solution

  • I'm not terribly good at f# (more like a novice), but this seems to work:

    let a = new Subject<int>()
    let b = new Subject<int>()
    
    let c = Observable.CombineLatest(a, b, Func<_,_,_>(fun x y -> x * y))
    
    c.Subscribe(fun x -> printfn "%i" x) |> ignore
    
    a.OnNext(2)
    b.OnNext(2)
    a.OnNext(3)
    b.OnNext(5)
    b.OnNext(6)
    a.OnNext(1)
    

    I get:

    4
    6
    15
    18
    6