PublishSubject with Kotlin coroutines (Flow)

前端 未结 2 2112
情深已故
情深已故 2021-02-05 06:21

I used a PublishSubject and I was sending messages to it and also I was listening for results. It worked flawlessly, but now I\'m not sure how to do the same thing with Kotlin\'

2条回答
  •  猫巷女王i
    2021-02-05 06:51

    ArrayBroadcastChannel in Kotlin coroutines is the one most similar to PublishSubject.

    1. Like PublishSubject, an ArrayBroadcastChannel can have multiple subscribers and all the active subscribers are immediately notified.
    2. Like PublishSubject, events pushed to this channel are lost, if there are no active subscribers at the moment.

    Unlike PublishSubject, backpressure is inbuilt into the coroutine channels, and that is where the buffer capacity comes in. This number really depends on which use case the channel is being used for. For most of the normal use cases, I just go with 10, which should be more than enough. If you push events faster to this channel than receivers consuming it, you can give more capacity.

提交回复
热议问题