what is the alternative in coroutines for `share()` of `RxJava`?

327 views Asked by At

I have a config file I am fetching it and as a result getting headers and list of query: String and based on the queries I should implement different requests I mean I have request1 for config and based on the result of request1 I should combine it with request2, request3 …. and these combinations I want to have parallel I know I can achieve this with RxJava using share() but how can I do it with Coroutines?

1

There are 1 answers

0
Adib Faramarzi On

Think of it in a non-coroutines way, What would you have done if the functions were not suspending and just regular functions?

You can store the values you emit in a variable and check If you already cached it, If you have, you can just return the values, otherwise, calculate those values.

If you have some advanced logic that needs to be listened to (like RxJava's Subjects), you can use Kotlin Coroutines Channels.

To create a channel, you can use Channel() or ConflatedBroadCastChannel() or other variants. If you want your channel to be exactly like RxJava's PublishSubject, you can use ConflatedBroadCastChannel:

val broadCastChannel = ConflatedBroadcastChannel<Int>()

You can use broadCastChannel.offer(value) to send values to the channel.

To receive values from the channel you can use a simple for-each loop:

for (i in broadCastChannel.openSubscription()) {
       //your values
}