问题
I need to determine whether two different approaches for handling Observables are equally valid, or if one will cause memory issues.
In the following example, foo$
and bar
are template variables that receive their values from a service. Each has its own Observable. In the component, bar
is explicitly given its value from a subscription and later ends that subscription in OnDestroy()
. foo$
, however, does not explicitly subscribe to a service but rather uses an async
pipe in the template.
Are foo$
and bar
both valid ways of displaying the service data, or is foo$
problematic because there is no unsubscribing for memory cleanup?
ExampleService:
Injectable()
export class ExampleService {
get foo$(): Observable<string> {
return data.from.api;
}
get bar$: Observable<string> {
return data.from.api;
}
}
ExampleComponent:
@Component({
template: `
<div>{{ foo$ | async }}</div>
<div>{{ bar }}</div>
`
})
export class ExampleComponent implements OnInit, OnDestroy {
public foo$ = this._exampleService.foo$;
public bar = '';
private _destroy$ = new Subject();
constructor(private _exampleService: ExampleService) {}
public ngOnInit() {
this._exampleService.bar$
.pipe(takeUntil(this._destroy$))
.subscribe(bar => this.bar = bar);
}
/**
* Cancel subscriptions.
*/
public ngOnDestroy() {
this._destroy$.next(true);
this._destroy$.complete();
}
}
回答1:
From angular team
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
So the async pipe takes care of subscribing and unwrapping the data as well as unsubscribing when the component is destroyed.
回答2:
NO, The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
来源:https://stackoverflow.com/questions/56033098/is-unsubscribe-needed-if-an-observable-uses-an-async-pipe