如何在rxJava中订阅到不同的线程池

时间:2015-06-29 18:42:50

标签: java concurrency reactive-programming rx-java observable

我现在正在我的程序中运行这一点

Observable.from(constituents.entrySet()).subscribeOn(Schedulers.newThread())
        .flatMap(Async.toAsync((Map.Entry<String, ConstituentInfo> entry) -> {
            logger.info(Thread.currentThread().getName());
            ConstituentInfo constituent = entry.getValue();

            String securityBySymbol = Redux.getSecurityBySymbol(entry.getKey());

            String company = UtilityMethods.getNestedJsonObject(securityBySymbol, "company");
            Integer compId = UtilityMethods.getIntegerFromJsonObject(company, "id");
            String companyName = UtilityMethods.getStringFromJsonObject(company, "name");
            String tier = UtilityMethods.getNestedJsonObject(securityBySymbol, "tier");
            String tierId = UtilityMethods.getStringFromJsonObject(tier, "id");
            String marketPlace = UtilityMethods.getStringFromJsonObject(tier, "name");
            String countryName = getCountryName(compId);

            constituent.setCompanyName(StringUtils.isBlank(companyName) ? NA : companyName);
            constituent.setMarketPlace(StringUtils.isBlank(marketPlace) ? NA : marketPlace);
            constituent.setCountryName(StringUtils.isBlank(countryName) ? NA : countryName);
            constituent.setTierId(StringUtils.isBlank(tierId) ? NA : tierId);

            return constituent;
        })).subscribeOn(Schedulers.newThread())
        .toList()
        .timeout(30, TimeUnit.MINUTES)
        .toBlocking()
        .single();

并且它同时运行,但它在RxComputationThreadPool上运行。我想知道如何使它在Schedulers.newThread()上运行,如果它会提高性能。

或者,如果它不能提高性能,有没有办法让下面的代码运行得更快?

1 个答案:

答案 0 :(得分:1)

toAsync超载需要Scheduler,而您不需要subscribeOncomputation()调度程序是所有调度程序中最低的调度程序。 io()很可能并且newThread()肯定会启动一个新线程,因此可能需要几百微秒才能执行第一个任务,但它们非常适合阻止I / O或网络调用,而这种延迟实际上并不存在物质