Redux可见的史诗,不会发送任何新动作 [英] redux-observable epic that doesn't send any new actions

查看:77
本文介绍了Redux可见的史诗,不会发送任何新动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是我是一个菜鸟,还没有完全理解这些东西应该如何工作,但是我在redux-observable中有一部史诗,我想以此作为创建承诺的一种方式,该承诺将分派行动并在解决之前,请等待其他操作。我通过将操作映射到'__ IGNORE __'来使其正常工作,但我真的不想这样做。有什么方法可以让史诗般的动作来完成,而不传递任何其他信息吗?

Might be that I'm a noob and not fully understanding how this stuff should work yet, but I have an epic in redux-observable in which I want to use as a way to create a promise which will dispatch an action and wait for a different action before resolving. I've got it working by mapping the action to '__IGNORE__' but I really don't want to do that. Is there any way to just have an epic handle an action, but not pass anything else on?

这是我的代码:

export const waitFor = (type, action) => new Promise((resolve, reject) => {
   const waitForResult = action$ => action$.ofType(type).do(() => resolve()).mapTo({type: "___IGNORE___"});
   registerEpic(waitForResult);

   action();
 });


推荐答案

您可以丢弃通过使用 .ignoreElements() RxJS运算符

You can throw away any next'd values from an observable chain by using the .ignoreElements() RxJS operator

action$.ofType(type)
  .do(() => resolve())
  .ignoreElements();

另一种这样做的方法(不再是非对错)是创建一个仅订阅的匿名Observable

Another way of doing this (no more right or wrong) is to create an anonymous Observable that just subscribes.

const waitForResultEpic = action$ => new Observable(observer =>
  action$.ofType(type)
    .subscribe(() => resolve())
);

这将隐式返回我们创建的订阅,因此它也附加到rootEpic的生命周期中。因为我们从不调用 observer.next(),所以该史诗从不发出任何值。就像 ignoreElements()

This is implicitly returning the subscription we create, so that it's attached to the lifecycle of our rootEpic as well. Because we never call observer.next(), this epic never emits any values; just like ignoreElements().

尽管您没有问,您最终可能会注意到您的史诗将永远运行,监听与 type 变量匹配的传入操作。这可能不是您想要的,如果您想匹配一次 然后完成。

Although you didn't ask, you may eventually notice that your epic will run forever, listening for that incoming action matching the type variable. This may not be not what you want, if you want to match once then complete.

您可以使用 .take(1) 运算符。

You can accomplish that using .take(1) operator.

const waitForResult = action$ =>
  action$.ofType(type)
    .take(1)
    .do(() => resolve())
    .ignoreElements();

Or

const waitForResult = action$ => new Observable(observer =>
  action$.ofType(type)
    .take(1)
    .subscribe({
      next: () => resolve(),
      error: err => observer.error(err),
      complete: () => observer.complete()
    })
);

在应用程序的整个生命周期内仅匹配一次-一旦收到,它将不再执行

This will only match once per the life of the application--once received it will never do it again.

这篇关于Redux可见的史诗,不会发送任何新动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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