|
| 1 | +package com.baeldung.reactive.controller; |
| 2 | + |
| 3 | +import java.math.BigDecimal; |
| 4 | +import java.time.Duration; |
| 5 | +import java.util.Random; |
| 6 | +import java.util.stream.Stream; |
| 7 | + |
| 8 | +import org.springframework.http.MediaType; |
| 9 | +import org.springframework.web.bind.annotation.GetMapping; |
| 10 | +import org.springframework.web.bind.annotation.PathVariable; |
| 11 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 12 | +import org.springframework.web.bind.annotation.RestController; |
| 13 | + |
| 14 | +import com.baeldung.reactive.model.Stock; |
| 15 | + |
| 16 | +import reactor.core.publisher.Flux; |
| 17 | +import reactor.util.function.Tuple2; |
| 18 | + |
| 19 | +@RestController |
| 20 | +@RequestMapping("/rtes") |
| 21 | +public class StockReactiveController { |
| 22 | + |
| 23 | + @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/stocks/{code}") |
| 24 | + public Flux<Stock> getStocks(@PathVariable String code) { |
| 25 | + BigDecimal startingPrice = new BigDecimal("100"); |
| 26 | + Flux<Stock> stockFlux = Flux.fromStream(Stream.generate(() -> new Stock( |
| 27 | + code, |
| 28 | + new Random().nextBoolean() ? |
| 29 | + startingPrice.add(BigDecimal.valueOf(new Random().nextDouble())): |
| 30 | + startingPrice.subtract(BigDecimal.valueOf(new Random().nextDouble()))))); |
| 31 | + Flux<Long> emmitFlux = Flux.interval(Duration.ofSeconds(1)); |
| 32 | + return Flux.zip(stockFlux, emmitFlux).map(Tuple2::getT1); |
| 33 | + } |
| 34 | + |
| 35 | + public static void main(String [] args) { |
| 36 | + |
| 37 | + } |
| 38 | +} |
0 commit comments