【问题标题】:Rxjs map only first emitionRxjs 仅映射第一次发射
【发布时间】:2018-11-21 00:43:37
【问题描述】:

有没有可以让我只映射第一个发射的运算符?

类似

import { from } from 'rxjs';
import { mapFirst } from 'rxjs/operators';

const source = from([1, 2, 3, 4, 5]);
const example = source.pipe(mapFirst(val => val + 10));
//output: 11,2, 3, 4, 5

【问题讨论】:

  • 查看索引map((value, index) => { if (index === 0) ... }
  • @cartant 谢谢,但我知道我可以做到这一点,我希望有一些自制的运算符,为了更好的语法:)

标签: rxjs


【解决方案1】:

如果你想写一个用户域操作符来做:

import { OperatorFunction } from "rxjs";
import { map } from "rxjs/operators";

function mapFirst<T, R>(selector: (value: T) => R): OperatorFunction<T, T | R> {
    return map<T, T | R>((value, index) => (index === 0) ? selector(value) : value);
}

你会像在你的问题中一样使用它。

【讨论】:

  • 谢谢,但有点遗憾,结果不能像[T, ...R]那样是类型安全的
【解决方案2】:

使用first 运算符或take(1)

const source = from([1, 2, 3, 4, 5]);
const example = source.pipe(first());

【讨论】:

  • 这不会在第一个值之后再发出
猜你喜欢
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多