You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让RxJS from()重复发射时跳过每个元素的首次发射?

问题原因分析

你当前的skip(1)位置错误,它作用在from(this.scheduleEntries)这个数据流上,会跳过整个数组的第一个元素,而非每个条目自身的首次发射。更关键的是,若试图把skip(1)放到单个条目的管道中(比如of(entry).pipe(skip(1), repeat(...))),of(entry)只会发射一次,skip(1)会直接吞掉这次发射,导致该条目完全没有输出——这就是你看不到任何发射的核心原因。

解决方案

要实现「每个条目跳过首次立即发射,之后永久重复按指定间隔发射」的需求,我们需要让每个条目先等待指定的countdown时间再进行第一次发射,之后重复这个等待-发射的循环。可以直接用timer作为初始延迟,配合repeat实现:

import { Observable, from, mergeMap, timer, repeat, map } from 'rxjs';

class Schedule {
  private scheduleEntries = [
    { value: true, countdown: 48395 },
    { value: true, countdown: 38395 },
    { value: false, countdown: 42394 },
    { value: true, countdown: 4835 },
  ];

  private lockEmitter$: Observable<ScheduleEntry>;

  constructor() {
    this.lockEmitter$ = from(this.scheduleEntries).pipe(
      mergeMap(entry => 
        // 先等待countdown时间,再发射entry,之后重复该过程
        timer(entry.countdown).pipe(
          map(() => entry),
          repeat({ 
            delay: () => timer(entry.countdown) 
          })
        )
      ),
    );
    this.lockEmitter$.subscribe(console.log);
  }
}

interface ScheduleEntry {
  value: boolean;
  countdown: number;
}
代码说明
  1. 对于每个scheduleEntries中的条目,用timer(entry.countdown)创建初始延迟Observable,等时间到后通过map转换成对应条目数据。
  2. repeat({ delay: () => timer(entry.countdown) })会在每次发射完成后,重新等待指定的countdown时间,再次发射条目,实现永久重复效果。
  3. 这种方式天然跳过了「条目首次立即发射」的逻辑,完全符合需求。

内容的提问来源于stack exchange,提问作者Schnitzler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:05:55