1

I want to send update every time the integer variable is changed

@PutMapping
public void update() {
    integer = random.nextInt();
}

@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Integer> eventFlux() {
    Flux<Integer> eventFlux = Flux.fromStream(
            Stream.generate(() -> integer)
    );
    return Flux.zip(eventFlux, onUpdate()).map(Tuple2::getT1);
}

private Flux<Long> onUpdate() {
    return Flux.interval(Duration.ofSeconds(1));
}
Marco R.
  • 2,667
  • 15
  • 33
umesh giri
  • 143
  • 1
  • 7
  • So, what is your question? are you getting any errors. Please explain your query clearly! – P3arl Jan 04 '20 at 07:05
  • As the code stands now, It's sending events every second, I was wondering how do I send event only when the Variable value is changed. Thanks. – umesh giri Jan 04 '20 at 07:16
  • Please go through this link if it helps you https://stackoverflow.com/questions/55923326/conditional-repeat-or-retry-on-mono-with-webclient-from-spring-webflux – P3arl Jan 04 '20 at 07:57

1 Answers1

2

You can use a FluxProcessor to work as an:

  • Upstream Subscriber; which you can use to add numbers to it:
    @PutMapping("/{number}")
    public void update(@PathVariable Integer number) {
        processor.onNext(number);
    }
  • Downstream Publisher (Flux); which clients can subscribe to receive the numbers added:
    @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Integer> eventFlux() {
        return processor;
    }

The following is a full working example of this:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxProcessor;

@SpringBootApplication
@EnableWebFlux
@RestController
public class EventStreamApp implements WebFluxConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(EventStreamApp.class);
    }

    private FluxProcessor<Integer, Integer> processor = DirectProcessor.create();

    @PutMapping("/{number}")
    public void update(@PathVariable Integer number) {
        processor.onNext(number);
    }

    @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Integer> eventFlux() {
        return processor;
    }
}

Complete code on GitHub

Hope this helps.

Marco R.
  • 2,667
  • 15
  • 33