Subscriptions are a convenient way to read a value from a data stream for your application logic. If unmanaged, they can create memory leaks in your application. A leaky application will consume ever-increasing amounts of RAM, eventually leading the browser tab to become unresponsive, leading to a negative perception of your app and, even worse, potential data loss, which can frustrate end users.
The source of a memory leak may not be obvious. In CurrentWeatherComponent
, we inject WeatherSevice
to access the value of BehaviorSubject
, currentWeather$
. If we mismanage subscriptions,currentWeather$
, we can end up with leaks in the component or the service.
Lifecycle of services
By default, Angular services are shared instance services or singletons automatically registered to a root provider. This means that, once created in memory, they’re kept alive as long as the app or feature module they’re a part of remains in memory. See the following...