gpt4 book ai didi

javascript - RxJS 发出字符串数组,彼此相隔一秒

转载 作者:行者123 更新时间:2023-12-05 02:41:09 25 4
gpt4 key购买 nike

我有一段代码负责获取 Observable<string[]> ,然后将其映射到 Observable<string>并发出彼此相隔 1 秒的值。

将其想象成网站上的消息自动收报机。

我当前的代码在下面运行:

    const arrayOfStrings$ = of([
'Warming things up',
'Getting things ready',
'Welcome'
]);

this.messages$ = arrayOfStrings$.pipe(
switchMap((messages) => from(messages).pipe(
concatMap((innerMessage) => of(innerMessage).pipe(delay(1000))),
)),
tap((message) => {
console.log(`Message: ${message}`);
})
);

有没有更好的方法用更少的代码来做到这一点?主要是switchMap()concatMap()彼此内心困扰着我。

感谢您的帮助和建议。

编辑:这是我在实际项目中运行的简化版本。我只是想找到一种更简单的方法来从 Observable 到 Observable 并在每次发射后将每次发射延迟一秒

最佳答案

您可以先展平数组,然后使用 concatMap() 延迟每次发射,这将确保一条一条地发射消息。

const arrayOfStrings$ = of([
'Warming things up',
'Getting things ready',
'Welcome'
]);

arrayOfStrings$
.pipe(
concatAll(), // flatten the array into individual next notifications
concatMap(message => of(message).pipe(
delay(1000),
)),
)
.subscribe();

关于javascript - RxJS 发出字符串数组,彼此相隔一秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68214987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com