如何将数据向下传递到反应链 [英] How to pass data down the reactive chain

查看:66
本文介绍了如何将数据向下传递到反应链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我需要将数据向下传递到反应链时,我最终都会做这样的事情:

Whenever I need to pass data down the reactive chain I end up doing something like this:

public Mono<String> doFooAndPassDtoAsMono(Dto dto) {
    return Mono.just(dto)
        .flatMap(dtoMono -> {
            Mono<String> result = // remote call returning a Mono
            return Mono.zip(Mono.just(dtoMono), result);
        })
        .flatMap(tup2 -> {
            return doSomething(tup2.getT1().getFoo(), tup2.getT2()); // do something that requires foo and result and returns a Mono
        });
}

给定以下示例 Dto 类:

Given the below sample Dto class:

class Dto {
    private String foo;

    public String getFoo() {
        return this.foo;
    }
}

因为一直压缩数据以将其向下传递(尤其是向下几级)通常会变得乏味,所以我想知道是否可以像这样直接引用 dto :

Because it often gets tedious to zip the data all the time to pass it down the chain (especially a few levels down) I was wondering if it's ok to simply reference the dto directly like so:

public Mono<String> doFooAndReferenceParam(Dto dto) {
       Mono<String> result = // remote call returning a Mono
        return result.flatMap(result -> {
            return doSomething(dto.getFoo(), result); // do something that requires foo and result and returns a Mono
        });
}

我对第二种方法的担忧是,假设订阅者在线程池上订阅了这个 Mono,我是否需要保证 Dto 是线程安全的(上面的例子很简单,因为它只携带一个 String 但如果不是)呢?

My concern about the second approach is that assuming a subscriber subscribes to this Mono on a thread pool would I need to guarantee that Dto is thread safe (the above example is simple because it just carries a String but what if it's not)?

另外,哪一种被认为是最佳实践"?

Also, which one is considered "best practice"?

推荐答案

案例很简单

  • 参考数据从一开始就可用(即在创建链之前),并且
  • 创建链以处理最多一个事件(即以 Mono 开头),并且
  • 参考数据是不可变的.

然后您可以简单地引用参数或局部变量中的参考数据——就像在您的第二个解决方案中一样.这完全没问题,没有并发问题.

Then you can simple refer to the reference data in a parameter or local variable – just like in your second solution. This is completely okay, and there are no concurrency issues.

强烈建议不要在反应式流中使用可变数据.如果你有一个可变的 Dto 类,你可能仍然可以使用它(假设正确同步)——但这会让你的代码的读者感到非常惊讶.

Using mutable data in reactive flows is strongly discouraged. If you had a mutable Dto class, you might still be able to use it (assuming proper synchronization) – but this will be very surprising to readers of your code.

这篇关于如何将数据向下传递到反应链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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