Skip to content

Commit 9073177

Browse files
Merge pull request #1834 from benjchristensen/toSerializedSubject
Subject.toSerialized
2 parents 14aeb00 + 3e9b3ee commit 9073177

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/main/java/rx/subjects/Subject.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import rx.Observable;
1919
import rx.Observer;
20+
import rx.Subscriber;
2021

2122
/**
2223
* Represents an object that is both an Observable and an Observer.
@@ -31,4 +32,23 @@ protected Subject(OnSubscribe<R> onSubscribe) {
3132
* @return true if there is at least one Observer subscribed to this Subject, false otherwise
3233
*/
3334
public abstract boolean hasObservers();
35+
36+
/**
37+
* Wraps a {@link Subject} so that it is safe to call its various {@code on} methods from different threads.
38+
* <p>
39+
* When you use an ordinary {@link Subject} as a {@link Subscriber}, you must take care not to call its
40+
* {@link Subscriber#onNext} method (or its other {@code on} methods) from multiple threads, as this could
41+
* lead to non-serialized calls, which violates the Observable contract and creates an ambiguity in the resulting Subject.
42+
* <p>
43+
* To protect a {@code Subject} from this danger, you can convert it into a {@code SerializedSubject} with code
44+
* like the following:
45+
* <p><pre>{@code
46+
* mySafeSubject = myUnsafeSubject.toSerialized();
47+
* }</pre>
48+
*
49+
* @return SerializedSubject wrapping the current Subject
50+
*/
51+
public final SerializedSubject<T, R> toSerialized() {
52+
return new SerializedSubject<T, R>(this);
53+
}
3454
}

0 commit comments

Comments
 (0)