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

Subject.toSerialized #1834

Merged
merged 1 commit into from
Nov 9, 2014
Merged
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
20 changes: 20 additions & 0 deletions src/main/java/rx/subjects/Subject.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import rx.Observable;
import rx.Observer;
import rx.Subscriber;

/**
* Represents an object that is both an Observable and an Observer.
Expand All @@ -31,4 +32,23 @@ protected Subject(OnSubscribe<R> onSubscribe) {
* @return true if there is at least one Observer subscribed to this Subject, false otherwise
*/
public abstract boolean hasObservers();

/**
* Wraps a {@link Subject} so that it is safe to call its various {@code on} methods from different threads.
* <p>
* When you use an ordinary {@link Subject} as a {@link Subscriber}, you must take care not to call its
* {@link Subscriber#onNext} method (or its other {@code on} methods) from multiple threads, as this could
* lead to non-serialized calls, which violates the Observable contract and creates an ambiguity in the resulting Subject.
* <p>
* To protect a {@code Subject} from this danger, you can convert it into a {@code SerializedSubject} with code
* like the following:
* <p><pre>{@code
* mySafeSubject = myUnsafeSubject.toSerialized();
* }</pre>
*
* @return SerializedSubject wrapping the current Subject
*/
public final SerializedSubject<T, R> toSerialized() {
return new SerializedSubject<T, R>(this);
}
}