1

I've got a number of reactive commands as well as some observables holding some information, and I'm trying to do something like:

_navigate = ReactiveCommand.Create(CanNavigate);
_navigate.CombineLatest(navigationTarget, (_, tgt) => tgt)
    .Subscribe(tgt => Navigation.NavigateTo(tgt));

I've tried a couple of different approaches:

  1. SelectMany
  2. Zip

I either end up with:

  1. Subscribe stops invoking after the first time (if I use Zip)
  2. Subscribe invokes even when the command hasn't been executed after it was executed once

Essentially I want:

An observable that triggers every time (and only) when the command has been executed, along with pulling in the most recent value of the second observable.

Can't quite get my head around how best to achieve this...

Clint
  • 6,133
  • 2
  • 27
  • 48

2 Answers2

6

If you are able to use a pre-release version the latest (2.3.0-beta2) has the method WithLatestFrom which does exactly this.

_navigate.WithLatestFrom(navigationTarget, (_, tgt) => tgt)
  .Subscribe(tgt => Navigation.NavigateTo(tgt));

If not you can create your own by doing:

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());
}

Source

paulpdaniels
  • 18,395
  • 2
  • 51
  • 55
1

we use Join to achive this behavoir.

the Idea is that at one moment you have one window for navigtion target and no window for _navigate command. When command appears, it takes the value from current open window of another sequence. The window for navigationTarget value closes, when new navigationTarget arrives.

_navigate.Join(
    navigationTarget,
    _ => Observable.Empty<Unit>(),
    _ => navigationTarget,
    (_, tgt) => tgt).Subscribe(tgt => Navigation.NavigateTo(tgt));
Dmitrii Dovgopolyi
  • 6,231
  • 2
  • 27
  • 44