Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WithLatestFrom #90

Closed
khellang opened this issue Apr 13, 2015 · 6 comments
Closed

Add WithLatestFrom #90

khellang opened this issue Apr 13, 2015 · 6 comments

Comments

@khellang
Copy link
Member

I'd ❤️ to see the withLatestFrom method from RxJava and RxJS be ported over to .NET as well.

Marbles

For reference: http://rxmarbles.com/#withLatestFrom

@james-world
Copy link

This is an implementation, if you want something quick:

public static IObservable<TResult> WithLatestFrom<TLeft, TRight, TResult>(
    this IObservable<TLeft> source,
    IObservable<TRight> other,
    Func<TLeft, TRight, TResult> resultSelector)
{
    return other.Publish(os =>
        source.SkipUntil(os)
              .Zip(os.MostRecent(default(TRight)), resultSelector));
}

@khellang
Copy link
Member Author

I have something like this that's working (I think 😝). Would love some feedback on it:

public static IObservable<TResult> WithLatestFrom<TResult, TFirst, TSecond>(
    this IObservable<TFirst> first,
    IObservable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    return Observable.Create<TResult>(observer =>
    {
        var published = first.Publish();

        var connection = published.Connect();

        var subscription = second
            .Select(a => published
                .Select(b => resultSelector(b, a)))
            .Switch()
            .Subscribe(observer);

        return new CompositeDisposable(connection, subscription);
    });
}

@james-world
Copy link

It passes my test, but it's got slightly more code in! ;) Looks fine though - nice approach. If you used the variant of Publish I used, you could get rid of the CompositeDisposable and the Create:

public static IObservable<TResult> WithLatestFrom<TLeft, TRight, TResult>(
    this IObservable<TLeft> source,
    IObservable<TRight> other,
    Func<TLeft, TRight, TResult> resultSelector)
{
    return source.Publish(os =>
        other.Select(a => os
            .Select(b => resultSelector(b,a)))
            .Switch());
}

@danyx23
Copy link

danyx23 commented Apr 24, 2015

👍
This is a pretty useful operator and should come with rx .net by default

@bartdesmet
Copy link
Collaborator

This operator has been added for the next release of Rx.NET.

@khellang
Copy link
Member Author

khellang commented May 3, 2015

Thanks, @bartdesmet! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants