订阅方法不会被 RxJS 触发 [英] subscribe method is not triggered with RxJS

查看:52
本文介绍了订阅方法不会被 RxJS 触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 RxJS 的初学者,我目前正在使用 RxJS@5 并且不了解我的代码的行为

I'm quite a beginner in RxJS, I'm currently using RxJS@5 and don't understand a behavior of my code

const currentExtentMinutes$ = initialExtentMinutes$
    .merge(selectedExtentMinutes$)
    .distinctUntilChanged()

// We message the worker that
// there is a new extent minutes
currentExtentMinutes$
  .subscribe(currentExtentMinutes => {
      console.log('send current extent', currentExtentMinutes);
      currentExtentMinutes => worker.postMessage({currentExtentMinutes});
  });

这很好用,但是一旦我添加了另一段代码,第一个订阅就不再起作用

This works great, but as soon as I add this other piece of code, the first subscribe doesn't work anymore

sortedTeams$.withLatestFrom(currentExtentMinutes$)
  .subscribe(([teams, extent]) => {
      const d3line = line()
        .x((pt, i) => scaleMinutes.invert(extent[0]) + scaleMinutes.invert(i))
        .y(scaleRanking)
        .curve(curveCardinal.tension(.5));
      const lines = gGraph.selectAll('.team-path').data(teams, _.get('name'));
      lines.enter().append('path')
        .attr('class', 'team-path')
        .style('stroke', team => `rgb(${team.colors[0]})`)
        .style('stroke-width', 7)
        .style('stroke-linecap', 'round')
        .style('stroke-linejoin', 'round')
        .style('fill', 'none')
        .merge(lines)
        .transition(t)
        .attr('d', team => d3line(team.ranking));
  });

我做错了吗?

推荐答案

我认为您可能是 observable 的热与冷性质的另一个受害者.基本上 currentExtentMinutes 订阅了两次,一次是在第一个代码片段中,第二次是使用 withLatestFrom.对冷 observable 的每次订阅都会重新启动生产者,重新产生值(有关更多详细信息,请查看 此处).

I think you might be yet another victim of the hot vs. cold nature of observables. Basically currentExtentMinutes is subscribed twice, once in the first code snippet, and the second time with the use of withLatestFrom. Every subscription to a cold observable will restart the producer, producing values anew (for more details have a look here).

如果这是这里的问题,那么与

If that is the problem here, then it should be enough to 'share' your cold observable with

const currentExtentMinutes$ = initialExtentMinutes$
    .merge(selectedExtentMinutes$)
    .distinctUntilChanged()
    .share()

这篇关于订阅方法不会被 RxJS 触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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