Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mnasyrov/pubsub
Simple PubSub for Typescript
https://github.com/mnasyrov/pubsub
emitter pubsub typescript
Last synced: about 2 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 (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T07:35:55.000Z (about 2 years ago)
- Last Synced: 2024-11-29T05:44:45.842Z (about 2 months ago)
- Topics: emitter, pubsub, typescript
- Language: TypeScript
- Homepage:
- Size: 1.17 MB
- Stars: 4
- Watchers: 3
- 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._
[![npm version](https://badge.fury.io/js/%40mnasyrov%2Fpubsub.svg)](https://www.npmjs.com/@mnasyrov/pubsub)
[![Actions Status](https://github.com/mnasyrov/pubsub/workflows/build/badge.svg)](https://github.com/mnasyrov/pubsub/actions)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](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)