@Override
@SuppressWarnings("unchecked")
public Observable<Void> flush() {
final long startTimeMillis = Clock.newStartTimeMillis();
eventsSubject.onEvent(metricEventProvider.getFlushStartEvent());
MultipleFutureListener existingListener =
unflushedWritesListener.getAndSet(new MultipleFutureListener(nettyChannel.newPromise()));
/**
* Do flush() after getting the last listener so that we do not wait for a write which is not flushed.
* If we do it before getting the existingListener then the write that happens after the flush() from the user
* will be contained in the retrieved listener and hence we will wait till the next flush() finish.
*/
nettyChannel.flush();
return existingListener.asObservable()
.doOnCompleted(new Action0() {
@Override
public void call() {
eventsSubject.onEvent(metricEventProvider.getFlushSuccessEvent(),
Clock.onEndMillis(startTimeMillis));