I'm looking for the best way to dispose chain with while(true) loop aka repeat operator. The problem I encountered is that sometimes when I dispose chain and something is still done in chain (for example socket write) result/exception won't be delivered. Most likely exception because socket is already closed and write produces SocketTimeout.
Logic: I have a Rx chain with repeat() operator. Stream reads packet from socket, does something with it and writes repsponse back to socket. Chain is disposed on service onStop() but sometime response was not yet send back before dispose. That makes my app to crash because exception wasn't handled correctly.
So there are two cases: 1. Nothing is done in chain when service is stopped and chain can be disposed immediatly. 2. Chain is working on request. In the meantime service was stopped, socket was closed but I want to wait for result and than dispose the chain.
Here is peace of my code:
mainLoopDisposable = Single.fromCallable { readStream(packet, socketInput) }
.map(::makeIpPacket)
.flatMap(doSomethingWithPacekt())
.doOnSuccess { socketOutput.write(it.rawPacket) }
.ignoreElement()
.retry(::retry)
.repeat()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({}, ::handleError)
Thanks for any suggestions!