spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.7k stars 38.14k forks source link

Expose property "complete" of ResponseBodyEmitter [SPR-16476] #21021

Closed spring-projects-issues closed 6 years ago

spring-projects-issues commented 6 years ago

Yanming Zhou opened SPR-16476 and commented

SseEmitter emitter = new SseEmitter();
while(!emitter.isComplete()){
    emitter.send();
}

//other thread could stop it by
emitter.complete();

Affects: 5.0.3

spring-projects-issues commented 6 years ago

Rossen Stoyanchev commented

We could expose the flag but I'm not sure it would really help. The send() can fail with the given sample code because another thread set "complete" after the while check and before the call to send. The flag can also be set through container events too, by the way, such as a timeout or error.

So you need to always expect a possible exception from send and at that point it becomes your check, i.e. you keep sending until you cannot any more:

while (true) {
    try {
        emitter.send();
    }
    catch (Exception ex) {
        // Done
    }
}
spring-projects-issues commented 6 years ago

Yanming Zhou commented

Yes, your suggestion is a better solution.