I just started learning RxJava and need help with a few questions to complete the task.
one.
I have a service that paints the figures and should return the figure after a delay — that is, a second (for circles) or two (for squares) after he was asked for it. You can not block the stream, you need to use timers.
While I was able to achieve a delay in this way, but it takes much more than a second. I added Scheduler , because without it, the result is not returned at all:
public Observable<PaintedCircle> paint(Shape shape) { return Observable .timer(1, TimeUnit.SECONDS, Schedulers.immediate()) .flatMap(x -> Observable.just(new PaintedCircle(shape.getSize()))); } I call this painting service from the code below (the code is still draft). In the same place, the figures are arranged in boxes of 5 pieces and displayed in the console:
public class Consumer { private static final int CIRCLE_MIN_SIZE = 30; public static void main(String[] args) { Producer producer = new Producer(); while (!producer.doesShouldStop()) { Observable.from(producer.produceShapes(40)) .filter(shape -> shape instanceof Square || shape instanceof Circle && shape.getSize() > CIRCLE_MIN_SIZE) .flatMap(shape -> shape.getPaintingService().paint(shape)) .buffer(5) .map(shapes -> new Box(shapes)) .forEach(System.out::println); } } } How to improve the implementation of the delay?
2
The second question concerns the creation of the figures themselves. Squares and circles should be created randomly and randomly sized. So far I have been using the usual Java for this, but it can probably also be done with the help of reactivity. So far my code looks like this:
public class Producer { private int MAX_SHAPE_SIZE = 100; private int counter; private boolean shouldStop; List<Shape> produceShapes(int amount) { List<Shape> shapes = new ArrayList<>(); Random random = new Random(); System.out.println("Produced following shapes:"); for (int i = 0; i < amount; i++) { int coin = random.nextInt(2); int size = Math.abs(random.nextInt(MAX_SHAPE_SIZE)); Shape shape = coin == 0 ? new Circle(size) : new Square(size); shapes.add(shape); System.out.print(shape); } System.out.println(); if (++counter == 3) { shouldStop = true; } return shapes; } boolean doesShouldStop() { return shouldStop; } } Can I rewrite this with RxJava?
In addition, according to the condition of the problem, Producer after three cycles, must inform Consumer 'y that there are no more figures. As you can see in Consumer code, while this is done using a while , but this also needs to be changed - probably with the help of a formal reply.
Please help.