本文介绍了组合最新,但只向左推的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个版本的 CombineLatest(这里我将其称为 WithLatest),它为左侧的每个项目和左侧的最新项目调用选择器对.它不应该只推动右侧的项目发生变化.

I need to implement a version of CombineLatest (I'll call it WithLatest here) that calls the selector for every item on the left and the latest item on the right. It shouldn't push for items on the right changing only.

我认为这是构建Observable.Create还是现有扩展的组合并不是特别重要;无论哪种方式,我都会将其设为盒装"扩展方法.

I think whether this is built Observable.Create or a combination of existing extensions is not particularly important; I'll be making this a "boxed" extension method either way.

示例

var left = new Subject<int>();
var right = new Subject<int>();

left.WithLatest(right, (l,r) => l + " " + r).Dump();

left.OnNext(1);   // <1>
left.OnNext(2);   // <2>
right.OnNext(1);  // <3>
right.OnNext(2);  // <4>
left.OnNext(3);   // <5>

应该屈服

2 1
3 2

编辑:我的例子的逻辑是:

  1. 左侧填充为 1.右侧为空,未推送任何值.
  2. Left 更新为 2(它忘记了以前的值).右边仍然是空的,所以什么都没有推.
  3. Right 填充了 1,因此 Left = 2(最新值),Right = 1 被推送.到目前为止,WithLatestCombineLatest
  4. 之间没有区别
  5. 右侧已更新 - 没有推送任何内容.这是什么不同
  6. Left 更新为 3,所以 Left = 3,Right = 2(最新值)被推送.

有人建议我尝试:


It's been suggested that I try:

var lr = right.ObserveOn(Scheduler.TaskPool).Latest();
left.Select(l => l + " " + lr.First()).Dump();

但这会阻塞当前线程以供我测试.

but this blocks on the current thread for my test.

推荐答案

您可以使用现有的运算符来做到这一点.

You can do this using existing operators.

Func<int, int, string> selector = (l, r) => l + " " + r;

var query = right.Publish(rs => left.Zip(rs.MostRecent(0), selector).SkipUntil(rs));

  • Publish 确保我们只订阅 right 一次,并在 rs 的所有订阅者之间共享订阅.

    • Publish ensures we only ever subscribe to right once and share the subscription among all subscribers to rs.

      MostRecentIObservable 转换为 IEnumerable,它总是从源可观察.

      MostRecent turns an IObservable<T> into an IEnumerable<T> that always yields the most recently emitted value from the source observable.

      Zip 介于 IObservableIEnumerable 之间,每次 observable 发出一个值时都会发出一个值.

      Zip between IObservable<T> and IEnumerable<U> emits a value each time the observable emits a value.

      SkipUntil 跳过出现在 right 发出值之前的对 (l, r).

      SkipUntil skips the pairs (l, r) which occur before right ever emits a value.

      这篇关于组合最新,但只向左推的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:57