title: How to implement a simple WebSocket based protocol using RxJava on Android
body: <p>I am writing a simple app to get started with RxJava, I am failing to figure out how to accomplish the following.</p>
  
  <p>I have a websocket connection, represented by a WebSocket object. The idea is to create an observable and start the WebSocket connection when someone subscribes to the observable.</p>
  
  <p>My custom Observable will then receive events from the WebSocket like onOpen(), onMessage(), onClosing() and onFailure(). When it receives this calls from the WebSocket it notifies the subscriber. And that sounds fine. Just call onNext() and provide the message.</p>
  
  <p>The part that's confusing to me is: what if my subscriber has to reply to these messages using the same WebSocket object?
  Here's what I have to do:</p>
  
  <ul>
  <li>I create a custom Observable than opens the WebSocket connection when subscribed to.</li>
  <li>At some point an observer subscribes to the observable.</li>
  <li>The observable opens the connection and starts routing messages coming from the server, to the observer.</li>
  <li>The observer uses some logic to figure out what to reply. Let's say it forwards the messages to some kind of state machine that ultimately returns the reply I have to send back to the server.</li>
  <li>Now someone has to send back the reply, possibly using a Reactive approach as well.</li>
  </ul>
  
  <p>So the question is, who is this someone?
  What is the best way to accomplish this in Rx? I suspect I should publish the replies to another Observable, but this other Observable would not have access to the WebSocket at all, therefore it would be unable to actually send replies.</p>
  
  <p>Am I responsible of carrying around the communication channel (WebSocket object) from the receiving Observable to the sending Observable? That sounds really wrong to me.</p>
  
  <p>Or should I just keep a shared WebSocket somewhere accessible to both Observables?</p>
  
  <p>Sorry if the question sounds stupid/trivial to someone but this is the first time I use RxJava and I fully realize the problem is that I am not currently "thinking Reactive", not yet.</p>