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 17
17
18
18
import rx .Observable ;
19
19
import rx .Observer ;
20
+ import rx .Subscriber ;
20
21
21
22
/**
22
23
* Represents an object that is both an Observable and an Observer.
@@ -31,4 +32,23 @@ protected Subject(OnSubscribe<R> onSubscribe) {
31
32
* @return true if there is at least one Observer subscribed to this Subject, false otherwise
32
33
*/
33
34
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
+ }
34
54
}
You can’t perform that action at this time.
0 commit comments