Skip to content

Commit

Permalink
Add addTeardown(). Closes #3. Closes #19. (#61)
Browse files Browse the repository at this point in the history
* Add `addTeardown()`. Closes #3. Closes #19.

* Remove old note

* Remove the syntactic sugar analogy

The intent with that analogy was to describe how *part* of `addTeardown()`
is syntactic sugar over immediately checking `subscriber.signal.aborted`,
and *otherwise* setting the given cleanup function to the signal's abort
handler, and also invoking it during `complete()` and `error()`, but that
latter part was not clear at all and was contradictory as @annevk pointed
out. So this commit removes the example, in favor of the earlier descriptive
text.

* chore: add more information about when teardown occurs.

---------

Co-authored-by: Ben Lesh <ben@benlesh.com>
  • Loading branch information
domfarolino and benlesh authored Sep 13, 2023
1 parent 70aa322 commit 8b9c989
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ interface Subscriber {
undefined next(any result);
undefined complete();
undefined error(any error);
undefined addTeardown(VoidFunction teardown);

readonly attribute AbortSignal signal;
};
Expand Down Expand Up @@ -378,9 +379,6 @@ observable.subscribe({
});
```
**Issue**: See https://github.com/domfarolino/observable/issues/3 about having
the Observable constructor being able to register teardown upon unsubscription.
While custom Observables can be useful on their own, the primary use case they
unlock is with event handling. Observables returned by the new
`EventTarget#on()` method are created natively with an internal callback that
Expand Down Expand Up @@ -457,6 +455,23 @@ observable.subscribe({next: data => {
}, signal: controller.signal});
```
#### Teardown
It is critical for an Observable subscriber to be able to register an arbitrary
teardown callback to clean up any resources relevant to the subscription. The
teardown can be registered from within the subscription callback passed into the
`Observable` constructor. When run (upon subscribing), the subscription callback
can register a teardown function via `subscriber.addTeardown()`.
If the subscriber has already been aborted (i.e., `subscriber.signal.aborted` is
`true`), then the given teardown callback is invoked immediately from within
`addTeardown()`. Otherwise, it is invoked synchronously:
- From `complete()`, after the subscriber's complete handler (if any) is
invoked
- From `error()`, after the subscriber's error handler (if any) is invoked
- The signal passed to the subscription is aborted by the user.
### Operators
Expand Down

0 comments on commit 8b9c989

Please sign in to comment.