Extension life cycle

As described in Life cycle, a LoopBackApplication has its own life cycles at runtime. Correspondingevents such as start and stop are emitted upon the state change. Please notethat LoopBack only support start and stop events for an application’s lifecycles at this moment.

Extension modules for LoopBack often contribute artifacts such as servers,datasources, and connectors to the application. They typically provide acomponent to bind such artifacts to the context together. Being able to listenon life cycle events is important for extension modules to collaborate with theapplication.

An extension module follows the same way as applications to implement andregister life cycle observers.

Implement a life cycle observer

A life cycle observer class optionally implements start and stop methods tobe invoked upon start and stop events emitted by an application’s life cyclerespectively.

  1. import {LifeCycleObserver} from '@loopback/core';
  2. export class MyLifeCycleObserver implements LifeCycleObserver {
  3. start() {
  4. // It can return `void` or `Promise<void>`
  5. }
  6. stop() {
  7. // It can return `void` or `Promise<void>`
  8. }
  9. }

A life cycle observer can be tagged with CoreTags.LIFE_CYCLE_OBSERVER_GROUP toindicate its group to be invoked for ordering. We can decorate the observerclass with @lifeCycleObserver to provide more metadata for the binding.

  1. import {lifeCycleObserver} from '@loopback/core';
  2. @lifeCycleObserver('g1')
  3. export class MyLifeCycleObserver {
  4. // ...
  5. }

Register a life cycle observer

A life cycle observer can be registered by calling lifeCycleObserver() of theapplication. It binds the observer to the application context with a specialtag - CoreTags.LIFE_CYCLE_OBSERVER.

  1. app.lifeCycleObserver(MyObserver);

Life cycle observers can be declared via a component class too. when thecomponent is mounted to an application, the observers are automaticallyregistered.

  1. export class MyComponentWithObservers implements Component {
  2. lifeCycleObservers = [XObserver, YObserver];
  3. }
  4. // Mount the component
  5. app.mount(MyComponentWithObservers);
  6. // Now `XObserver` and `YObserver` are registered in the application.