简体   繁体   中英

How do I specify scheduler for Flux.generate

How do I specify scheduler for Flux.generate ? I have blocking call inside it which I'd like to be able to cancel. So far I hacked it via

Flux<Integer> generate = Flux.generate(....);
Mono<List<Integer>> fut =
        Flux.just("ignored")
                .publishOn(Schedulers.single())
                .flatMap(ignored -> generate)
                .timeout(Duration.ofSeconds(2), Flux.empty())

Is there more idiomatic way?

Use subscribeOn

        Flux<Integer> g1 = Flux.generate(c -> {
            System.out.println(Thread.currentThread());
            c.next(1);
        });

        System.out.println(g1.take(5).collectList().block());

        Flux<Integer> g2 = g1.subscribeOn(Schedulers.elastic());

        System.out.println(g2.take(5).collectList().block());

Output

Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
[1, 1, 1, 1, 1]
Thread[elastic-2,5,main]
Thread[elastic-2,5,main]
Thread[elastic-2,5,main]
Thread[elastic-2,5,main]
Thread[elastic-2,5,main]
[1, 1, 1, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM