I'm currently trying to implement tcp watchdog / retry system using rx, your help would be greatly appreciated.
Having an observable, I would like to have an Observable as a result of periodically checking if we can still write to the socket. Easy enough, I can do something like this:
class SocketSubscribeFunc implements Observable.OnSubscribeFunc<Socket> {
private final String hostname;
private final int port;
private Socket socket;
SocketSubscribeFunc(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public Subscription onSubscribe(final Observer<? super Socket> observer) {
try {
log.debug("Trying to connect...");
socket = new Socket(hostname, port);
observer.onNext(socket);
} catch (IOException e) {
observer.onError(e);
}
return new Subscription() {
public void unsubscribe() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
}
Observable<Socket> socketObservable = Observable.create(new SocketSubscribeFunc(hostname,port));
Observable<Boolean> watchdog = Observable.combineLatest(socketObservable, Observable.interval(1, TimeUnit.SECONDS), new Func2<Socket, Long, Boolean>() {
public Boolean call(final Socket socket, final Long aLong) {
try {
socket.getOutputStream().write("ping\n".getBytes());
return true;
} catch (IOException e) {
return false;
}
}
});
, (/ ) (/ ).
Observable, OnSubscribeFunc .
, Watchervables.
switchMap/..., .
, . :)
!