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();
}
}