在RxJava流中添加线程池

时间:2014-12-09 10:42:57

标签: java multithreading asynchronous concurrency rx-java

我想知道是否可以使用 RxJava 库以便在以下用例中添加一些并发性:

  • 使用自定义String(类似ResultSet
  • 从现有Observable顺序获取ResultSetObservable.create(resultSet)
  • 为每个值调用Web服务(例如,使用InvokeWebServiceFunc1<String, Pair<String, Integer>>()实例),以便检索与String相关的一些统计信息(请注意String中的Pair ExportAsCSVAction1<Pair<String, Integer>>(PrintStream printStream)与输入中传递的内容相同
  • 以CSV格式打印所有内容(使用ResultSetObservable.create(resultSet) .map(new InvokeWebServiceFunc1<String, Pair<String, Integer>>()) .subscribe(new ExportAsCSVAction1<Pair<String, Integer>>(System.out)); )。

所以这就是我所拥有的:

String

它运行良好,但由于Web服务可能需要一些时间来进行ExportAsCSVAction0输入,我想通过添加一些并发性来创建映射行为的线程池(例如10个线程)但我需要 toBlocking().forEach()在同一个线程中调用(实际上当前线程是完美的)。

你能帮帮我吗?我无法确定使用Schedulers.from(fixedThreadPool)模式是否是正确的解决方案,我不明白在哪里使用observeOn()(在subscribeOn()或{{1}}中)

感谢您的帮助!

1 个答案:

答案 0 :(得分:20)

我自己找到了!

package radium.rx;

import java.util.List;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.schedulers.Schedulers;

public class TryRx {

    public static Random RANDOM = new Random();

    public static void main(String[] arguments) throws Throwable {
        final List<Integer> inputs = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
        final ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2);

        Iterable<Integer> outputs = Observable.<Integer>from(inputs)
                .flatMap((Integer input) -> deferHeavyWeightStuff(input).subscribeOn(Schedulers.from(threadPoolExecutor)))
                .toBlocking()
            .toIterable();

        for (Integer output : outputs) {
            System.out.println(output);
        }

        threadPoolExecutor.shutdown();
    }

    public static void sleepQuietly(int duration, TimeUnit unit) {
        try {
            Thread.sleep(unit.toMillis(duration));
        } catch (InterruptedException e) {

        }
    }

    public static Observable<Integer> deferHeavyWeightStuff(final int input) {
        return Observable.defer(() -> Observable.just(doHeavyWeightStuff(input)));
    }

    public static int randomInt(int min, int max) {
        return RANDOM.nextInt((max - min) + 1) + min;
    }

    public static int doHeavyWeightStuff(int input) {
        sleepQuietly(randomInt(1, 5), TimeUnit.SECONDS);
        int output = (int) Math.pow(input, 2);
        return output;
    }

}

干杯!