Skip to content

Instantly share code, notes, and snippets.

@PrabhatKJena
Last active February 27, 2024 12:28
Show Gist options
  • Save PrabhatKJena/1f565460d21ad48a5ff0cab82a44b6a1 to your computer and use it in GitHub Desktop.
Save PrabhatKJena/1f565460d21ad48a5ff0cab82a44b6a1 to your computer and use it in GitHub Desktop.
Reactive Implementation demo
import java.io.IOException;
import java.util.Random;
import java.util.function.Consumer;
class ReactiveImplDemo {
public static void main(String[] args) throws IOException {
System.out.println("Start");
ReactiveSource.getIntFlux(20).subscribe(x -> System.out.println("Subscriber 1 received int: " + x));
ReactiveSource.getIntFlux(12).subscribe(x -> System.out.println(" Subscriber 2 received int: " + x));
System.out.println("End. Press any key to continue");
System.in.read();
}
}
class ReactiveSource {
public static Flux<Integer> getIntFlux(int limit) {
final Flux<Integer> integerFlux = new Flux<>();
new Thread(() -> {
final DownStream downStream = new DownStream();
int i = 1;
while (i <= limit) {
int anInt = downStream.generateNextInt();
integerFlux.consumer.accept(anInt);
i++;
}
}).start();
return integerFlux;
}
}
class Flux<T> {
Consumer<T> consumer;
public void subscribe(Consumer<T> consumer) {
this.consumer = consumer;
}
}
class DownStream {
final Random random = new Random();
public int generateNextInt() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return random.nextInt(1000);
}
}
@PrabhatKJena
Copy link
Author

Output


Start
End. Press any key to continue
                 Subscriber 2 received int: 330
Subscriber 1 received int: 924
Subscriber 1 received int: 870
                 Subscriber 2 received int: 563
Subscriber 1 received int: 408
                 Subscriber 2 received int: 913
Subscriber 1 received int: 11
                 Subscriber 2 received int: 42
                 Subscriber 2 received int: 127
Subscriber 1 received int: 623
                 Subscriber 2 received int: 656
Subscriber 1 received int: 49
                 Subscriber 2 received int: 367
Subscriber 1 received int: 624
                 Subscriber 2 received int: 91
Subscriber 1 received int: 113
                 Subscriber 2 received int: 249
Subscriber 1 received int: 911
Subscriber 1 received int: 50
                 Subscriber 2 received int: 97
Subscriber 1 received int: 936
                 Subscriber 2 received int: 673
                 Subscriber 2 received int: 872
Subscriber 1 received int: 794
Subscriber 1 received int: 955
Subscriber 1 received int: 634
Subscriber 1 received int: 97
Subscriber 1 received int: 851
Subscriber 1 received int: 389
Subscriber 1 received int: 253
Subscriber 1 received int: 2
Subscriber 1 received int: 37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment