Skip to content

utility function for creating observables for closeable resources #1282

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

Merged
merged 2 commits into from
Jul 8, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
*/
package rx.observables;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observable.Operator;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
Expand All @@ -27,15 +37,10 @@
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observable.Operator;
import rx.Subscriber;
import rx.functions.Func1;
import rx.functions.Func2;

public class StringObservable {
/**
* Reads from the bytes from a source {@link InputStream} and outputs {@link Observable} of
Expand All @@ -50,6 +55,73 @@ public class StringObservable {
public static Observable<byte[]> from(final InputStream i) {
return from(i, 8 * 1024);
}

private static class CloseableResource<S extends Closeable> implements Subscription {
private final AtomicBoolean unsubscribed = new AtomicBoolean();
private S closable;

public CloseableResource(S closeable) {
this.closable = closeable;
}

@Override
public void unsubscribe() {
if (unsubscribed.compareAndSet(false, true)) {
try {
closable.close();
} catch (Exception e) {
throw new RuntimeException(e);
Copy link
Collaborator

Choose a reason for hiding this comment

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

This approach will be useful sometimes but other times I will want an error on close to be suppressed. This is a common pattern for reading from an InputStream. Once we call close() we have finished our reading and just want to clean up and if the resource has already been closed or invalidated we don't really care. I'm unaware what behaviour results when unsubscribe itself throws an exception and can't write a test at the moment.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There is a unit test for each of the ending closing conditions that you can step through. The basic pattern is that unsubscribe, onComplete or onError the SafeSubscribe will ignore any additional exceptions.

}
}
}

@Override
public boolean isUnsubscribed() {
return unsubscribed.get();
}
}

/**
* Func0 that allows throwing an {@link IOException}s commonly thrown during IO operations.
* @see StringObservable#from(UnsafeFunc0, UnsafeFunc1)
*
* @param <R>
*/
public static interface UnsafeFunc0<R> extends Callable<R> {
public R call() throws Exception;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I might have missed something here. I don't see that the UnsafeFunc0 adds much. After all every Func0 is potentially unsafe inasmuch as it can throw a RuntimeException for instance.

}

/**
* Helps in creating an Observable that automatically calls {@link Closeable#close()} on completion, error or unsubscribe.
*
* <pre>
* StringObservable.using(() -> new FileReader(file), (reader) -> StringObservable.from(reader))
* </pre>
*
* @param resourceFactory
* Generates a new {@link Closeable} resource for each new subscription to the returned Observable
* @param observableFactory
* Converts the {@link Closeable} resource into a {@link Observable} with {@link #from(InputStream)} or {@link #from(Reader)}
* @return
*/
public static <R, S extends Closeable> Observable<R> using(final UnsafeFunc0<S> resourceFactory,
final Func1<S, Observable<R>> observableFactory) {
return Observable.using(new Func0<CloseableResource<S>>() {
@Override
public CloseableResource<S> call() {
try {
return new CloseableResource<S>(resourceFactory.call());
} catch (Throwable e) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

So the net effect of UnsafeFunc0 is that it forces us to catch the declared Exception on resourceFactory.call() and think about what might happen. I'm not sure it's worth it.

throw new RuntimeException(e);
}
}
}, new Func1<CloseableResource<S>, Observable<R>>() {
@Override
public Observable<R> call(CloseableResource<S> t1) {
return observableFactory.call(t1.closable);
}
});
}

/**
* Reads from the bytes from a source {@link InputStream} and outputs {@link Observable} of
Expand Down Expand Up @@ -320,10 +392,24 @@ public byte[] call(String str) {
* @return the Observable returing all strings concatenated as a single string
*/
public static Observable<String> stringConcat(Observable<String> src) {
return src.reduce(new Func2<String, String, String>() {
return toString(src.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() {
@Override
public String call(String a, String b) {
return a + b;
public StringBuilder call(StringBuilder a, String b) {
return a.append(b);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nice optimization

}
}));
}

/**
* Maps {@link Observable}&lt;{@link Object}&gt; to {@link Observable}&lt;{@link String}&gt; by using {@link String#valueOf(Object)}
* @param src
* @return
*/
public static Observable<String> toString(Observable<?> src) {
return src.map(new Func1<Object, String>() {
@Override
public String call(Object obj) {
return String.valueOf(obj);
}
});
}
Expand Down Expand Up @@ -429,11 +515,11 @@ private void output(String part) {
* @return an Observable which emits a single String value having the concatenated
* values of the source observable with the separator between elements
*/
public static <T> Observable<String> join(final Observable<T> source, final CharSequence separator) {
return source.lift(new Operator<String, T>() {
public static Observable<String> join(final Observable<String> source, final CharSequence separator) {
return source.lift(new Operator<String, String>() {
@Override
public Subscriber<T> call(final Subscriber<? super String> o) {
return new Subscriber<T>(o) {
public Subscriber<String> call(final Subscriber<? super String> o) {
return new Subscriber<String>(o) {
boolean mayAddSeparator;
StringBuilder b = new StringBuilder();

Expand All @@ -455,12 +541,12 @@ public void onError(Throwable e) {
}

@Override
public void onNext(Object t) {
public void onNext(String t) {
if (mayAddSeparator) {
b.append(separator);
}
mayAddSeparator = true;
b.append(String.valueOf(t));
b.append(t);
}
};
}
Expand Down
Loading