Angular provides a manualCleanup
configuration option for effects, preventing automatic cleanup when the owner component/service is destroyed.
With manualCleanup: true
, you gain control but must manually call .destroy()
on the EffectRef
that is returned by your effect
to release resources like intervals or subscriptions.
Remember, with great power comes great responsibility!
[00:00] Usually, we want the effect to get cleaned up automatically whenever the owner of the effect, whether it's a component or something else, gets destroyed. However, sometimes we want more control over it. So an effect accepts a second parameter with some configuration options. In this case, we are interested in the manual [00:19] cleanup flag, which we'll set to true. After setting the manual cleanup to true, the effect won't get cleaned up automatically so that when we display the child and the effect gets started, we can see that the length of the array gets displayed. However, when we turn off, like we uncheck the checkbox, [00:39] it's still running. So since we got manual control, we are responsible for manually cleaning it up. And this is where mentioned earlier, the effect ref comes into play. So let's create a simple button which is going to run a method whenever the button gets clicked. So let's call it just simply [00:59] cleanup. And let's put an click handler which is going to run a cleanup method which we'll execute and define over here. So the cleanup method is simply going to access what is the time effect reference and there is a [01:19] destroy method which will going to run. So now, there is no effect, our application has been reloaded and when we display and create the child, we can see that the effect is running. However, we are manually responsible for cleaning up. So when I click the button, the effect has been cleaned up. [01:39] However, bear in mind that right now we are responsible for actually executing this timer effect dot destroy. So if we forget to do it, there is no way to later clean up the resources. So with great power comes great responsibility in this case.