java 事件订阅,具有多个订阅者和事件的RxJava并发

I'm looking for a way to attach multiple subscribers to an RxJava Observable stream, with each subscriber processing emitted events asynchronously.

I first tried using .flatMap() but that didn't seem to work on any subsequent subscribers. All subscribers were processing events on the same thread.

.flatMap(s -> Observable.just(s).subscribeOn(Schedulers.newThread()))

What ended up working was consuming each event in a new thread by creating a new Observable each time:

Observable.from(Arrays.asList(new String[]{"1", "2", "3"}))

.subscribe(j -> {

Observable.just(j)

.subscribeOn(Schedulers.newThread())

.subscribe(i -> {

try {

Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("s1=>" + Thread.currentThread().getName() + "=>" + i);

});

});

Output:

s1=>RxNewThreadScheduler-1=>1

s1=>RxNewThreadScheduler-2=>2

s1=>RxNewThreadScheduler-3=>3

And the end result with multiple subscribers:

ConnectableObservable e = Observable.from(Arrays.asList(new String[]{"1", "2", "3"}))

.publish();

e.subscribe(j -> {

Observable.just(j)

.subscribeOn(Schedulers.newThread())

.subscribe(i -> {

try {

Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));

} catch (InterruptedException e1) {

e1.printStackTrace();

}

System.out.println("s1=>" + Thread.currentThread().getName() + "=>" + i);

});

});

e.subscribe(j -> {

Observable.just(j)

.subscribeOn(Schedulers.newThread())

.subscribe(i -> {

try {

Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));

} catch (InterruptedException e1) {

e1.printStackTrace();

}

System.out.println("s2=>" + Thread.currentThread().getName() + "=>" + i);

});

});

e.connect();

Output:

s2=>RxNewThreadScheduler-4=>2

s1=>RxNewThreadScheduler-1=>1

s1=>RxNewThreadScheduler-3=>2

s2=>RxNewThreadScheduler-6=>3

s2=>RxNewThreadScheduler-2=>1

s1=>RxNewThreadScheduler-5=>3

However, this seems a little clunky. Is there a more elegant solution or is RxJava just not a good use case for this?

解决方案

You can achieve it with Flowable and parallel:

Flowable.fromIterable(Arrays.asList("1", "2", "3"))

.parallel(3)

.runOn(Schedulers.newThread())

.map(item -> {

try {

Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));

} catch (InterruptedException e1) {

e1.printStackTrace();

}

System.out.println("s1=>" + Thread.currentThread().getName() + "=>" + item);

return Completable.complete();

})

.sequential().subscribe();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值