1

I'm creating a WebSocket class to receive some data and I'm trying to use Flowable with FlowableEmitter to receive the socket response.

I want to hold the emitter and every time I receive the data I call onNext and handle the result, it work fine if I do a subscribe in every flowable, but doesn't work if I use FlatMap to send another message after the first flowable receive the data.

I create a List of emitter:

var listEmitter: MutableList<FlowableEmitter<*>> = mutableListOf()

Then I create a function to register the observer:

inline fun <reified T> onMessage(data: ByteString?): Flowable<T> {
    return Flowable.create<T>({ emitter ->
        listEmitter.add(emitter)
        //send the data to socket
        data?.let { socket?.send(data) }
    }, BackpressureStrategy.LATEST)
}

When I receive the data from socket I call:

//I called [0] here to demonstrate the logic only
((listEmitter[0].subscriber) as FlowableEmitter<Any>).onNext(true)

And in my presenter I try to do something like:

socket
    .onMessage(/*some ByteString*/)
    .flatMap {
        if (it) {
            socket.onMessage(/*other data*/)
        } else {
            Flowable.just(false)
        }
    }.flatMap {
        if (it) {
            socket.onMessage(/*other data*/)
        } else {
            Flowable.just(false)
        }
    }.subscribe { /* do some stuff */}

So with that Only the first FlatMap is trigger, the second and third is never trigger, I call the onNext on the correct emitter, but nothing happened, the onNext is called, the FlatMap is not called.

The data that I send on "onMessage" has an identifier so in the WebSocketConnection I know the correct emitter, but to simplify I didn't do that here

I'm not sure why is not working and don't know how i can archive that.I want to send onMessage only after the first one receive the result.

tiagoMissiato
  • 305
  • 3
  • 16
  • An emitter is for one subscriber so you can't reuse them or multicast via them. Try `PublishProcessor` to notify multiple subscribers of the same events. – akarnokd Sep 14 '18 at 07:55
  • @akarnokd I don't want to have multiple subscriber receiving the same data from one Emitter, I wan that each subscriber receive a specific data and passes to flatmap so I can send another message, PublishProcessor have the same behavior as FlowableEmitter, SingleEmitter, etc. If I have one Subscriber to each onMessage it works, but the second flatMap doesn't. Not sure if what I want is possible. – tiagoMissiato Sep 14 '18 at 13:52

0 Answers0