https://github.com/mnasyrov/pubsub
Simple PubSub for Typescript
https://github.com/mnasyrov/pubsub
emitter pubsub typescript
Last synced: 11 months ago
JSON representation
Simple PubSub for Typescript
- Host: GitHub
- URL: https://github.com/mnasyrov/pubsub
- Owner: mnasyrov
- License: mit
- Created: 2019-08-19T14:50:54.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T07:35:55.000Z (over 3 years ago)
- Last Synced: 2025-07-11T18:30:57.698Z (12 months ago)
- Topics: emitter, pubsub, typescript
- Language: TypeScript
- Homepage:
- Size: 1.17 MB
- Stars: 5
- Watchers: 2
- Forks: 1
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Simple PubSub
_Implements Publisher/Subscriber pattern. Provides a value emitter, subscription and consumer interface. Supports Typescript._
[](https://www.npmjs.com/@mnasyrov/pubsub)
[](https://github.com/mnasyrov/pubsub/actions)
[](https://conventionalcommits.org)
## Usage
Install dependencies:
```bash
$ npm install --save @mnasyrov/pubsub
```
Create an emitter and publish a value to consumers:
```typescript
import {Emitter} from '@mnasyrov/pubsub';
// Declare a value emitter.
const emitter = new Emitter();
// Subscribe by a listener.
const subscription = emitter.subscribe(value => {
console.log(value);
});
// Emit a value.
emitter.emit(42);
// Cancel a subscription.
subscription.unsubscribe();
```
## Public API
```typescript
/** Allows to cancel a subscription. It is compatible with RxJS/Subscription. */
export interface Subscription {
unsubscribe(): void;
}
export type Consumer = (value: T) => any;
export interface Publisher {
subscribe(consumer: Consumer): Subscription;
}
export interface Emitter {
constructor();
/** A number of subscribed consumers. */
readonly size: number;
/** Subscribes a consumer of values. */
subscribe(consumer: Consumer): Subscription;
/** Emits a value to subscribed consumers. */
emit(value: T);
/** Removes all subscribed consumers. */
clear();
}
```
## License
[MIT](LICENSE)