Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Rx's CombineLatest and default initial values

Given 2 types A and B with default values d(A) & d(B). And 2 Subjects:

let sa = new Subject<A>()
let sb = new Subject<B>()

And a function f of type A -> B -> C

I created this observable:

let o = Observable.CombineLatest(sa, sb, f)

However, I need o to produce an initial value based on the d(A) & d(B). The docs say that CombineLatest will only produce its first output once both subjects have produce their first output.

I have 2 approaches, but I don't know which will work/ which is the best or if I'm missing some operator that already does what I need.

The first approach I came up is to manually call OnNext to sa and sb with the default values after the relevant subscriptions to o have been made.

My second approach is to use BehaviorSubjects instead of plain Subjects, create them with the initial values and hope that CombineLatest will use that for its first output.

Thanks for reading.

Addendum I've confirmed that the 2nd approach works, but still I don't know if introducing a BehaviorSubject instead of a plain Subject is the best for this case.

like image 997
Lay González Avatar asked May 29 '15 22:05

Lay González


1 Answers

How about using StartWith?

public static Observable<T> StartWithDefault(this Observable<T> observable) {
    return observable.StartWith(default(T));
}

Then:

sa.StartWithDefault().CombineLatest(sb.StartWithDefault(), f)
like image 145
Craig Gidney Avatar answered Sep 18 '22 13:09

Craig Gidney