我需要将一些上下文传播到 Project Reactor 中的下游运算符,但看起来他们只允许以自下而上的方式这样做,如所述 in the documentation .
有没有办法将它从上游运营商传播到下游?我可以用这样的包装器想象一个解决方法,但我真的很想避免这种情况:
private static class Contextualized<T> {
private final Map<Object, Object> context;
private final T content;
public Contextualized(T content) {
context = new HashMap<>();
this.content = content;
}
public Contextualized(Map<Object, Object> context, T content) {
this.context = context;
this.content = content;
}
public Map<Object, Object> getContext() {
return context;
}
public T getContent() {
return content;
}
}
public void someFunction() {
Mono.just(new Contextualized<>(1))
.map(it -> new Contextualized<>(Map.of("operation", "added 1"), it.getContent() + 1))
.doOnNext(it -> System.out.println(it.getContext().get("operation").toString()))
.subscribe();
...
}
最佳答案
您当前的解决方案很好。你可以接受它。
这可能是另一种方式。但可能不是一个优雅的解决方案。
Flux.range(1, 5)
.materialize() // convert the object to Signal<Object>
.map(o -> {
Context context = o.getContext().put("name", "somename");
return o.isOnNext() ? Signal.next(o.get(), context) : Signal.complete(context);
})
...
...
.doOnNext(s -> System.out.println(s.getContext().get("name").toString())) // access ctx variables
.dematerialize() // convert the signal to regular object and lose the context here
https://stackoverflow.com/questions/64254127/
相关文章:
c# - 无法在启动类中注入(inject)IAntiforgery
javascript - 错误 : Jmeter: Typed variable declarati
python - 我试图将 python 文件转换为 exe 文件,但它不起作用
reactjs - 在 useEffect Hook 中使用 axios 取消 token 时如何修
asp.net-core - 我可以在 AspNetCore WebAPI 中将 Cancellat
javascript - 来自 firebase 的图像的 html2canvas jsPdf 访问
html - 使一个 div 填充具有未指定尺寸的表格单元格的整个宽度和高度