简体   繁体   English

如何结束 spring web 通量中的嵌套订阅?

[英]How to end nested subscriptions in spring web flux?

I am trying to have my app so that when a new entry is added to the back end, the front end is notified of the new changes through event source.我正在尝试使用我的应用程序,以便在将新条目添加到后端时,通过事件源将新更改通知前端。 The code is shown below, this all seems to work well, but I am not sure if making a subscription in a method (getAllShifts) like that is good practice as I am not sure how it gets disposed?代码如下所示,这一切似乎都运行良好,但我不确定在这样的方法(getAllShifts)中订阅是否是一种好习惯,因为我不确定它是如何处理的? Does the subscription end when the client closes the app or the event source ends?当客户端关闭应用或事件源结束时订阅是否结束? Any guidance on that would be helpful.任何有关这方面的指导都会有所帮助。

@Service
public class ShiftService {

    @Autowired
    ShiftRepository shiftRepository;

    private Sinks.Many<Shift> sink = Sinks.many().replay().latest();

    public Mono<Shift> addShift(Shift shift) throws InterruptedException {
        Mono<Shift> shiftt = shiftRepository.save(shift);
        return shiftt
                .doOnSuccess(u -> this.sink.tryEmitNext(u));
    }


   
    public Flux<Shift> getAllShifts() {
 
        this.shiftRepository.findAll().subscribe(u -> this.sink.tryEmitNext(u));
        return sink.asFlux();
    }
}

Another question, if we make a subscription to a Mono, do we need to dispose it or does it take care of itself as there is just one item to be emitted?另一个问题,如果我们订阅 Mono,我们是否需要处理它,或者它是否会自行处理,因为只有一个项目要发出?

Yes.是的。 Subscribe should not be used.不应使用订阅。 You let the framework subscribe.你让框架订阅。 You can very well use the same onSuccess on this您可以很好地在此使用相同的onSuccess

return this.shiftRepository.findAll().doOnsuccess(u -> this.sink.tryEmitNext(u));返回 this.shiftRepository.findAll().doOnsuccess(u -> this.sink.tryEmitNext(u));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM