|
| 1 | +package com.baeldung.reactive.generator; |
| 2 | + |
| 3 | +import com.baeldung.reactive.model.Email; |
| 4 | +import org.springframework.stereotype.Component; |
| 5 | +import reactor.core.publisher.Flux; |
| 6 | + |
| 7 | +import java.time.Duration; |
| 8 | +import java.util.*; |
| 9 | + |
| 10 | +@Component |
| 11 | +public class EmailGenerator { |
| 12 | + private static Map<String, Email> emailMap = new HashMap<String, Email>() { |
| 13 | + { |
| 14 | + put("emailBob", new Email("Hello", "Hello Bob")); |
| 15 | + put("emailRob", new Email("Hello1", "Hello Rob")); |
| 16 | + put("emailJeff", new Email("Hello2", "Hello Jeff")); |
| 17 | + put("emailTom", new Email("Hello3", "Hello Tom")); |
| 18 | + put("emailBobby", new Email("Hello4", "Hello Bobby")); |
| 19 | + } |
| 20 | + }; |
| 21 | + |
| 22 | + public Flux<Email> fetchQuoteStream() { |
| 23 | + return Flux.interval(Duration.ofSeconds(1)) |
| 24 | + .onBackpressureDrop() |
| 25 | + .map(this::generateEmail) |
| 26 | + .flatMapIterable(emails -> emails); |
| 27 | + } |
| 28 | + |
| 29 | + /* |
| 30 | + * Create an email for all tickers |
| 31 | + */ |
| 32 | + private List<Email> generateEmail(long interval) { |
| 33 | + Object[] emailKeys = emailMap.keySet() |
| 34 | + .toArray(); |
| 35 | + List<Email> emailList = new ArrayList<>(); |
| 36 | + |
| 37 | + // select random email message from emailMap |
| 38 | + emailList.add(emailMap.get(emailKeys[new Random().nextInt(emailKeys.length)])); |
| 39 | + return emailList; |
| 40 | + } |
| 41 | +} |
0 commit comments