File tree Expand file tree Collapse file tree 1 file changed +20
-0
lines changed
src/main/java/rx/subjects Expand file tree Collapse file tree 1 file changed +20
-0
lines changed Original file line number Diff line number Diff line change 1717
1818import rx .Observable ;
1919import 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}
You can’t perform that action at this time.
0 commit comments