简体   繁体   English

RX如何将命令与另一个可观察到的结合

[英]Rx how to combine command with another observable

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) 订阅在第一次后停止调用(如果我使用Zip)
  2. Subscribe invokes even when the command hasn't been executed after it was executed once 即使命令执行一次后仍未执行,Subscribe也会被调用

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... 无法完全了解如何最好地实现这一目标...

If you are able to use a pre-release version the latest (2.3.0-beta2) has the method WithLatestFrom which does exactly this. 如果您能够使用预发行版本,则最新的(2.3.0-beta2)具有方法WithLatestFrom可以完全WithLatestFrom这一点。

_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 资源

we use Join to achive this behavoir. 我们使用Join实现此行为。

the Idea is that at one moment you have one window for navigtion target and no window for _navigate command. 这个想法是在一个时刻,你有一个windownavigtion target并没有窗口_navigate命令。 When command appears, it takes the value from current open window of another sequence. 当出现命令时,它将从另一个序列的当前打开的窗口中获取值。 The window for navigationTarget value closes, when new navigationTarget arrives. 当新的navigationTarget到达时, navigationTarget值的窗口关闭。

_navigate.Join(
    navigationTarget,
    _ => Observable.Empty<Unit>(),
    _ => navigationTarget,
    (_, tgt) => tgt).Subscribe(tgt => Navigation.NavigateTo(tgt));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM