class BlockingOperatorToIterator {

    public static <T> Iterator<T> toIterator(Observable<? extends T> source) {
        final BlockingQueue<Notification<? extends T>> notifications = new LinkedBlockingQueue<Notification<? extends T>>();

        // using subscribe instead of unsafeSubscribe since this is a BlockingObservable "final subscribe"
        final Subscription subscription = source.materialize().subscribe(new Subscriber<Notification<? extends T>>() {
            @Override
            public void onCompleted() {
                // ignore
            }

            @Override
            public void onError(Throwable e) {
                notifications.offer(Notification.<T>createOnError(e));
            }

            @Override
            public void onNext(Notification<? extends T> args) {
                notifications.offer(args);
            }
        });

        return new Iterator<T>() {
            private Notification<? extends T> buf;

            @Override
            public boolean hasNext() {
                if (buf == null) {
                    buf = take();
                }
                if (buf.isOnError()) {
                    throw Exceptions.propagate(buf.getThrowable());
                }
                return !buf.isOnCompleted();
            }

            @Override
            public T next() {
                if (hasNext()) {
                    T result = buf.getValue();
                    buf = null;
                    return result;
                }
                throw new NoSuchElementException();
            }

            private Notification<? extends T> take() {
                try {
                    return notifications.take();
                } catch (InterruptedException e) {
                    subscription.unsubscribe();
                    throw Exceptions.propagate(e);
                }
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Read-only iterator");
            }
        };
    }

    private  BlockingOperatorToIterator();

}