How to end nested subscriptions in spring web flux?

Viewed 24

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? 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?

1 Answers

Yes . Subscribe should not be used. You let the framework subscribe. You can very well use the same onSuccess on this

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

Related