6

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. TIA.

RxJS version: 6.4.0

Angular version: 7.2

Community
  • 1
  • 1
danday74
  • 52,471
  • 49
  • 232
  • 283

2 Answers2

8

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:

Vlad274
  • 6,514
  • 2
  • 32
  • 44
  • @danday74 Did you ever get that "new way"? – dstj Apr 15 '19 at 22:26
  • here's a clue from a ts lint warning ... WARNING: C:/Users/daniel/Desktop/biblical-hebrew/biblical-hebrew-fe/src/app/services/websocket.service.ts[34, 29]: create is deprecated: use new Subject() instead – danday74 Apr 21 '19 at 01:40
  • this still remains the one tslint warning in my codebase :( – danday74 Apr 23 '19 at 22:57
  • @danday74 Updated with additional research. If that detail is not sufficient, I recommend you ask a new question with additional information such as what parameters you're using and how you're using the result – Vlad274 Apr 24 '19 at 00:22
0

Subject will not accept any arguments while creating. So you need to initialize it like (new Subject()). After then you can use next method on it to emit value.

gaurav soni
  • 206
  • 1
  • 10