使用PublishSubject和flatMap实现并发

时间:2018-04-20 12:46:26

标签: android kotlin rx-java rx-java2

我正在尝试构建一个Android服务,其中包含项目列表(LIST),并且希望对每个项目执行任务(任务可以是上载或下载任务)。

  • 当任务正在进行时,可以动态地向LIST添加更多项目,并且可以重新排列列表中的项目(如果尚未处理项目)。
  • 我希望随时同时处理n任务。

这是我在阅读不同的在线资源后尝试的内容;不幸的是它不起作用。

val scheduler = Schedulers.from(Executors.newFixedThreadPool(1))
val publishSubject = PublishSubject.create<Pair<String, String>>()
publishSubject
    .subscribeOn(Schedulers.io())
    .flatMap({ it ->
        io.reactivex.Observable.fromCallable { it }
            .subscribeOn(scheduler)
                .map { pair ->
                {
                    println("Op in progress")
                    SystemClock.sleep(4000) // simulate network operating and a heap of other operations
                }
            }
    }, 5 /* concurrency */)
    .subscribe()

首先,我有要处理的项目列表,这些项目将作为

发布
LIST.forEach {
    publishSubject.onNext(it)
}

当我要处理其他项目时,我会调用

publishSubject.onNext(item)

从日志中,我可以看到publishSubject.onNext(item)被调用。但是,println("Op in progress")未被调用,我可以看到没有相应的日志输出。

非常感谢任何帮助。

合并@akarnokd的评论后

更新代码段

val scheduler = Schedulers.from(Executors.newFixedThreadPool(5))
val publishSubject = PublishSubject.create<Pair<String, String>>()
publishSubject
    .flatMap({ it ->
        io.reactivex.Observable.just(it)
            .subscribeOn(scheduler)
                .map { pair ->
                    println("Op in progress")
                    SystemClock.sleep(4000) // simulate network operating and a heap of other operations
            }
    }, 5 /* concurrency */)
    .subscribe()

0 个答案:

没有答案