Rx how to combine command with another observable

点点圈 提交于 2019-12-02 11:06:13

问题


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...


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/31168020/rx-how-to-combine-command-with-another-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!