Options
All
  • Public
  • Public/Protected
  • All
Menu

Class LifecycleResource<T>

deprecated

When possible, you'll want to favor Resource over LifecycleResource as Resource is simpler.

They key differences are that the LifecycleResource base class has 3 lifecycle hooks

  • setup - called upon first access of the resource
  • update - called when any tracked used during setup changes
  • teardown - called when the containing context is torn down

The main advantage to the LifecycleResource is that the teardown hook is for "last teardown", whereas with Resource, if a destructor is registered in the destructor, there is no way to know if that destruction is the final destruction.

An example of when you'd want to reach for the LifecycleResource is when you're managing external long-lived state that needs a final destruction call, such as with XState, which requires that the "State machine interpreter" is stopped when you are discarding the parent context (such as a component).

An example

import { LifecycleResource } from 'ember-resources';
import { createMachine, interpret } from 'xstate';

const machine = createMachine(); // ... see XState docs for this function this ...

class MyResource extends LifecycleResource {
@tracked state;

setup() {
this.interpreter = interpret(machine).onTransition(state => this.state = state);
}

update() {
this.interpreter.send('ARGS_UPDATED', this.args);
}

teardown() {
this.interpreter.stop();
}
}

Using this Resource is the exact same as Resource

import { useResource } from 'ember-resources';

class ContainingClass {
state = useResource(this, MyResource, () => [...])
}

There is however a semi-unintuitive technique you could use to continue to use Resource for the final teardown:

import { Resource } from 'ember-resources';
import { registerDestructor, unregisterDestructior } from '@ember/destroyable';

class MyResource extends Resource {
constructor(owner, args, previous) {
super(owner, args, previous);

registerDestructor(this, this.myFinalCleanup);

if (previous) {
// prevent destruction
unregisterDestructor(prev, prev.myFinalCleanup);
} else {
// setup
}
}

@action myFinalCleanup() { }
}

Type parameters

Hierarchy

  • LifecycleResource

Index

Constructors

Properties

Methods

Constructors

Properties

args: T

Methods

  • setup(): void
  • Returns void

  • teardown(): void
  • Returns void

  • update(): void
  • Returns void

  • with<Args, SubClass>(thunk: Thunk): SubClass

Generated using TypeDoc