Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/connorjameslow/subject-matter
https://github.com/connorjameslow/subject-matter
Last synced: 2 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/connorjameslow/subject-matter
- Owner: ConnorJamesLow
- Created: 2022-07-10T05:45:45.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-07-10T05:49:54.000Z (over 2 years ago)
- Last Synced: 2023-03-07T19:21:33.194Z (almost 2 years ago)
- Language: TypeScript
- Size: 33.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
A simple `Subject` for the observer pattern.
## Documentation
### `Subject` Class
Holds a bit of state and a list of subscribers.#### Constructor
Requires one parameter representing the initial state.```ts
const subject = new Subject(0);
```#### Protected Fields
If you'd like to extend `Subject`, note the following protected (using typescript) fields are available
- `__data: T`: the current state.
- `__observers: Record>`: a record of all currently subscribed observers.#### Methods
- `subscribe(observer: Observer): Unsubscriber`: adds an observer to notify when a change is pushed. Also immediately calls the observer with the current state.
- `push(next: T): void`: push a change to observers. Other overloads:
- `push(resolve: Updater): void`#### Type Declaration
Where `T` is the type of data passed to the `Subject` instance.```ts
type Observer = (d?: T) => any;
type Unsubscriber = () => boolean;
type Updater = (v?: T) => T;
```### Example
```ts
// Create a new Subject (T = string)
const subject = new Subject('world');// Add an observer:
const unsubscribe = subject.subscribe(v => console.log(`hello ${v}`)); // logs "hello world"// Push an update
subject.push('there'); // logs "hello there"// Unsubscribe observer when done listening for changes.
unsubscribe(); // returns true
// subject.push('...') won't call the above observer anymore.
```