Rx 如何将命令与另一个 observable 结合 [英] Rx how to combine command with another observable

查看:33
本文介绍了Rx 如何将命令与另一个 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. 邮编

我要么得到:

  1. 订阅在第一次之后停止调用(如果我使用 Zip)
  2. 即使命令执行一次后还没有执行,订阅也会调用

基本上我想要:

每次(并且)在命令执行时触发的 observable,同时拉入第二个 observable 的最新值.

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

推荐答案

如果您能够使用预发布版本,则最新 (2.3.0-beta2) 具有方法 WithLatestFrom正是这个.

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

来源

这篇关于Rx 如何将命令与另一个 observable 结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆