Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reactive Observable for UsingLatest
/// <summary>
/// Creates an observable that will attach the latest value from a second source observable for each value.
/// </summary>
/// <typeparam name="TSource1">The source observable</typeparam>
/// <typeparam name="TSource2">The attached observable</typeparam>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="source1">The type of the incoming observable</param>
/// <param name="source2">The type of the attached observable</param>
/// <param name="resultSelector"></param>
/// <returns>An observable that is the result of applying <paramref name="resultSelector"/> on the two observables</returns>
/// <remarks>Unlike CombineLatest does not propogate on values from the second observable</remarks>
public static IObservable<TResult> UsingLatest<TSource1, TSource2, TResult>(this IObservable<TSource1> source1,
IObservable<TSource2> source2, Func<TSource1, TSource2, TResult> resultSelector) where TSource2 : new()
{
return source1.UsingLatest(source2, default(TSource2), resultSelector);
}
public static IObservable<TResult> UsingLatest<TSource1, TSource2, TResult>(this IObservable<TSource1> source1,
IObservable<TSource2> source2,
TSource2 defaultValue,
Func<TSource1, TSource2, TResult> resultSelector)
{
return Observable.Create<TResult>(observer =>
{
TSource2 lastValue = defaultValue;
var innerObserver = Observer.Create<TSource2>(x => lastValue = x, observer.OnError);
var innerSubscription2 = source2.SubscribeSafe(innerObserver);
var innerSubscription1 = source1
.Select(x => resultSelector(x, lastValue))
.SubscribeSafe(observer);
return new CompositeDisposable(innerSubscription1, innerSubscription2);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment