subscribe method is not triggered with RxJS

别说谁变了你拦得住时间么 提交于 2019-12-11 08:02:13

问题


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

Am I doing something wrong ?


回答1:


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


来源:https://stackoverflow.com/questions/38142278/subscribe-method-is-not-triggered-with-rxjs

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