import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.functions.BiConsumer;
import io.reactivex.rxjava3.functions.BiFunction;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Supplier;

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Observable<Observable<Integer>> inf = Observable.interval(10, TimeUnit.SECONDS)
                .map(i -> {
                    System.out.println("Next observable");
                    return i;
                })
                .map(Main::rangeInf);

        Observable.switchOnNext(inf)
                .subscribe(System.out::println);

        Thread.sleep(1000000);
    }

    public static Observable<Integer> rangeInf(Long from) {
        Supplier<Integer> s = () -> 1;

        BiFunction<Integer, Emitter<Integer>, Integer> nxt = (integer, integerEmitter) -> {
            integerEmitter.onNext(integer);
            delay();
            return integer + 1;
        };
        Observable<Integer> inf = Observable.generate(s, nxt);

        return inf;
    }

    public static void delay() {
        int random = (int)(Math.random() * 3 + 1);
        try {
            Thread.sleep(random * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}