angularrxjs

rxjs Subject.create deprecated - what should I use instead?


I have this code in a service in my Angular app:

const subby = Subject.create(observer, observable)

But my IDE correctly marks Subject.create as deprecated. What should I use instead thanks? I've tried new Subject(observer, observable) but no joy.

RxJS version: 6.4.0
Angular version: 7.2


Solution

  • Looking at the source code, the static function Subject.create(destination, source) is just a wrapper around new AnonymousSubject<T>(destination, source).

    If you're just looking to deal with the warning, you can change your code to

    import { AnonymousSubject } from 'rxjs/internal/Subject';
    
    const subby = new AnonymousSubject<T>(observer, observable);
    

    RxJs has documented their motivation for this change here. The important quote:

    Subject.create doesn't actually create a Subject, but rather an AnonymousSubject, which I would REALLY like to rename as FrankenSubject because that describes what it is, you basically glue an Observer to an Observable and call it a "Subject".

    In short, using Subject.create (or the AnonymousSubject object) is a confusing way of accomplishing your goals.

    You can look at the source code for this class here, but the gist is that it's a pointless class that obfuscates what's going on. In the code, you can see that destination and source (the Observer and Observable arguments) have NO interaction.

    So, the "right way" to fix the code is to murder this object entirely and be more explicit about how the relevant events are routed.

    For example:

    // This code...
    const subby = Subject.create(observer, observable);
    subby.subscribe((value: value) => console.log(value));
    subby.next("Test");
    
    // Should be replace by this code
    // Nothing
    observable.subscribe((value: value) => console.log(value));
    observer.next("Test");
    

    I also found the following warnings about using Subject.create that may be relevant for future readers: