java flowable,如何在RxJava中明确表示Flowable的完成?

I'm trying to create a Flowable which is wrapping an Iterable. I push elements to my Iterable periodically but it seems that the completion event is implicit. I don't know how to signal that processing is complete. For example in my code:

// note that this code is written in Kotlin

val iterable = LinkedBlockingQueue()

iterable.addAll(listOf(1, 2, 3))

val flowable = Flowable.fromIterable(iterable)

.subscribeOn(Schedulers.computation())

.observeOn(Schedulers.computation())

flowable.subscribe(::println, {it.printStackTrace()}, {println("completed")})

iterable.add(4)

Thread.sleep(1000)

iterable.add(5)

Thread.sleep(1000)

This prints:

1

2

3

4

completed

I checked the source of the Flowable interface but it seems that I can't signal that a Flowable is complete explicitly. How can I do so? In my program I publish events which have some delay between them and I would like to be explicit when to complete the event flow.

Clarification:

I have a long running process which emits events. I gather them in a queue and I expose a method which returns a Flowable which wraps around my queue. The problem is that there might be already elements in the queue when I create the Flowable. I will process the events only once and I know when the flow of events stops so I know when I need to complete the Flowable.

解决方案

Using .fromIterable is the wrong way to create a Flowable for your use case.

Im not actually clear on what that use case is, but you probably want to use Flowable.create() or a PublishSubject

val flowable = Flowable.create( {

it.onNext(1)

it.onNext(2)

it.onComplete()

}, BackpressureStrategy.MISSING)

val publishSubject = PublishSubject.create()

val flowableFromSubject = publishSubject.toFlowable(BackpressureStrategy.MISSING)

//This data will be dropepd unless something is subscribed to the flowable.

publishSubject.onNext(1)

publishSubject.onNext(2)

publishSubject.onComplete()

Of course how you deal with back-pressure will depend on the nature of the source of data.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值