Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added: BO.Latest, fixed: BO.next, BO.mostRecent, BO.toIterable #626

Merged
merged 3 commits into from
Dec 23, 2013
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions rxjava-core/src/main/java/rx/observables/BlockingObservable.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.operators.OperationLatest;
import rx.operators.OperationMostRecent;
import rx.operators.OperationNext;
import rx.operators.OperationToFuture;
Expand Down Expand Up @@ -266,6 +267,24 @@ public Iterable<T> next() {
return OperationNext.next(o);
}

/**
* Returns the latest item emitted by the underlying Observable, waiting if necessary
* for one to become available.
* <p>
* If the underlying observable produces items faster than the Iterator.next() takes them
* onNext events might be skipped, but onError or onCompleted events are not.
* <p>
* The difference between BlockingObservable.next() and BlockingObservable.latest() is that
* the former does not overwrite untaken values whereas the latter does.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description is confusing. I think for BlockingObservable.next(), the next() of Iteratoralways returns the next incoming value. For BlockingObservable.latest(), the next() of Iterator will first check if there is an untaken value. If so, return the untaken value and clear it. If not, block and wait for the next incoming value.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. BO.next() traps the next value only if there is someone asking for it in It.next(). How about I just remove this comparison paragraph?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to remove it as it's inaccurate. I guess @DavidMGross will help us draw a nice marble diagram to show the differences :)

* <p>
* Note also that an onNext() directly followed by onCompleted() might hide the given onNext() event.
*
* @return the Iterable sequence
*/
public Iterable<T> latest() {
return OperationLatest.latest(o);
}

/**
* If the {@link Observable} completes after emitting a single item, return that item,
* otherwise throw an exception.
Expand Down
184 changes: 184 additions & 0 deletions rxjava-core/src/main/java/rx/operators/OperationLatest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.operators;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import rx.Notification;
import rx.Observable;
import rx.Observer;
import rx.util.Exceptions;

/**
* Wait for and iterate over the latest values of the source observable.
* If the source works faster than the iterator, values may be skipped, but
* not the onError or onCompleted events.
*/
public final class OperationLatest {
/** Utility class. */
private OperationLatest() { throw new IllegalStateException("No instances!"); }

public static <T> Iterable<T> latest(final Observable<? extends T> source) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
LatestObserverIterator<T> lio = new LatestObserverIterator<T>();
source.subscribe(lio);
return lio;
}
};
}

/** Observer of source, iterator for output. */
static final class LatestObserverIterator<T> implements Observer<T>, Iterator<T> {
final Lock lock = new ReentrantLock();
final Semaphore notify = new Semaphore(0);
// observer's values
boolean oHasValue;
Notification.Kind oKind;
T oValue;
Throwable oError;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using materialize to pack the all kinds of messages is better

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know. One less memory allocation seemed a good saving.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using materialize and Notification makes the code clearer, doesn't it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, okay, I'll change things around.

@Override
public void onNext(T args) {
boolean wasntAvailable;
lock.lock();
try {
wasntAvailable = !oHasValue;
oHasValue = true;
oValue = args;
oKind = Notification.Kind.OnNext;
} finally {
lock.unlock();
}
if (wasntAvailable) {
notify.release();
}
}

@Override
public void onError(Throwable e) {
boolean wasntAvailable;
lock.lock();
try {
wasntAvailable = !oHasValue;
oHasValue = true;
oValue = null;
oError = e;
oKind = Notification.Kind.OnError;
} finally {
lock.unlock();
}
if (wasntAvailable) {
notify.release();
}
}

@Override
public void onCompleted() {
boolean wasntAvailable;
lock.lock();
try {
wasntAvailable = !oHasValue;
oHasValue = true;
oValue = null;
oKind = Notification.Kind.OnCompleted;
} finally {
lock.unlock();
}
if (wasntAvailable) {
notify.release();
}
}

// iterator's values

boolean iDone;
boolean iHasValue;
T iValue;
Throwable iError;
Notification.Kind iKind;

@Override
public boolean hasNext() {
if (iError != null) {
Exceptions.propagate(iError);
}
if (!iDone) {
if (!iHasValue) {
try {
notify.acquire();
} catch (InterruptedException ex) {
iError = ex;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we catch the InterruptedException, we need to call Thread.currentThread().interrupt(); so that other codes interested in InterruptedException can be notified. And since an exception happens, I think hasNext should return false.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I overlooked it. Actually, other similar cases just throw Exceptions.propagate(ex);.

iHasValue = true;
iKind = Notification.Kind.OnError;
return true;
}

lock.lock();
try {
iKind = oKind;
switch (oKind) {
case OnNext:
iValue = oValue;
oValue = null; // handover
break;
case OnError:
iError = oError;
oError = null; // handover
if (iError != null) {
Exceptions.propagate(iError);
}
break;
case OnCompleted:
iDone = true;
break;
}
oHasValue = false;
} finally {
lock.unlock();
}
iHasValue = true;
}
}
return !iDone;
}

@Override
public T next() {
if (iKind == Notification.Kind.OnError) {
Exceptions.propagate(iError);
}
if (hasNext()) {
if (iKind == Notification.Kind.OnNext) {
T v = iValue;
iValue = null; // handover
iHasValue = false;
return v;
}
}
throw new NoSuchElementException();
}

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

}
}
12 changes: 6 additions & 6 deletions rxjava-core/src/main/java/rx/operators/OperationMostRecent.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@
*/
public final class OperationMostRecent {

public static <T> Iterable<T> mostRecent(final Observable<? extends T> source, T initialValue) {

MostRecentObserver<T> mostRecentObserver = new MostRecentObserver<T>(initialValue);
final MostRecentIterator<T> nextIterator = new MostRecentIterator<T>(mostRecentObserver);

source.subscribe(mostRecentObserver);
public static <T> Iterable<T> mostRecent(final Observable<? extends T> source, final T initialValue) {

return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
MostRecentObserver<T> mostRecentObserver = new MostRecentObserver<T>(initialValue);
final MostRecentIterator<T> nextIterator = new MostRecentIterator<T>(mostRecentObserver);

source.subscribe(mostRecentObserver);

return nextIterator;
}
};
Expand Down
13 changes: 6 additions & 7 deletions rxjava-core/src/main/java/rx/operators/OperationNext.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,18 @@
public final class OperationNext {

public static <T> Iterable<T> next(final Observable<? extends T> items) {

NextObserver<T> nextObserver = new NextObserver<T>();
final NextIterator<T> nextIterator = new NextIterator<T>(nextObserver);

items.materialize().subscribe(nextObserver);

return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
NextObserver<T> nextObserver = new NextObserver<T>();
final NextIterator<T> nextIterator = new NextIterator<T>(nextObserver);

items.materialize().subscribe(nextObserver);

return nextIterator;
}
};

}

private static class NextIterator<T> implements Iterator<T> {
Expand Down
20 changes: 10 additions & 10 deletions rxjava-core/src/main/java/rx/operators/OperationToIterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package rx.operators;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

Expand Down Expand Up @@ -63,27 +64,26 @@ public void onNext(Notification<? extends T> 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 (buf == null) {
buf = take();
if (hasNext()) {
T result = buf.getValue();
buf = null;
return result;
}
if (buf.isOnError()) {
throw Exceptions.propagate(buf.getThrowable());
}

T result = buf.getValue();
buf = null;
return result;
throw new NoSuchElementException();
}

private Notification<? extends T> take() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import static org.junit.Assert.*;

import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Assert;

import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -201,6 +203,58 @@ public void testToIterable() {
assertEquals(false, it.hasNext());

}
@Test(expected = NoSuchElementException.class)
public void testToIterableNextOnly() {
BlockingObservable<Integer> obs = BlockingObservable.from(Observable.from(1, 2, 3));

Iterator<Integer> it = obs.toIterable().iterator();

Assert.assertEquals((Integer)1, it.next());
Assert.assertEquals((Integer)2, it.next());
Assert.assertEquals((Integer)3, it.next());

it.next();
}

@Test(expected = NoSuchElementException.class)
public void testToIterableNextOnlyTwice() {
BlockingObservable<Integer> obs = BlockingObservable.from(Observable.from(1, 2, 3));

Iterator<Integer> it = obs.toIterable().iterator();

Assert.assertEquals((Integer)1, it.next());
Assert.assertEquals((Integer)2, it.next());
Assert.assertEquals((Integer)3, it.next());

boolean exc = false;
try {
it.next();
} catch (NoSuchElementException ex) {
exc = true;
}
Assert.assertEquals(true, exc);

it.next();
}

@Test
public void testToIterableManyTimes() {
BlockingObservable<Integer> obs = BlockingObservable.from(Observable.from(1, 2, 3));

Iterable<Integer> iter = obs.toIterable();

for (int j = 0; j < 3; j++) {
Iterator<Integer> it = iter.iterator();

Assert.assertTrue(it.hasNext());
Assert.assertEquals((Integer)1, it.next());
Assert.assertTrue(it.hasNext());
Assert.assertEquals((Integer)2, it.next());
Assert.assertTrue(it.hasNext());
Assert.assertEquals((Integer)3, it.next());
Assert.assertFalse(it.hasNext());
}
}

@Test(expected = TestException.class)
public void testToIterableWithException() {
Expand Down
Loading