An open API service indexing awesome lists of open source software.

https://github.com/32bitkid/kefir.handle

Kefir.withHandler() adapter to accept a syntax more like Kefir.observe()
https://github.com/32bitkid/kefir.handle

Last synced: 5 months ago
JSON representation

Kefir.withHandler() adapter to accept a syntax more like Kefir.observe()

Awesome Lists containing this project

README

          

# kefir.handle

Adapts the generic `withHandler(handler)` format to work more like the syntax `observe(observer)`.

## Installation

### NPM

```
npm install kefir.handle
```

## Usage

```js
import handle from 'kefir.handle';

stream.withHandler(handle({
value(emitter, value, event) { /* ...do stuff... */ },
error(emitter, value, event) { /* ...do stuff... */ },
end(emitter, value, event) { /* ...do stuff... */ },
}));
```

A handler is an object with 3 optional methods:

- `value` - called when the source observable emits a value
- `error` - called when the source observable emits an error
- `end` - called when the source observable has ended

Each of these handlers are invoked with three arguments: an emitter, the value of the event, and an event object.

Please note, an `undefined` handler will _automatically_ re-emit events of that type:

```js
import Kefir from 'kefir';
import handle from 'kefir.handle';

var source = Kefir.sequentially(100, [0, 1, 2, 3]);
var result = source .withHandler(handler());

result.log();
```

```
> [sequentially.withHandler] 1
> [sequentially.withHandler] 2
> [sequentially.withHandler] 3
> [sequentially.withHandler]
```

```
source: ---0---1---2---3X
result: ---•---•---•---•X
0 1 2 3
```

This is _the opposite_ of the way that `Kefir.withHandler()` works. If you _want_ to discard events, you can use the exported `throwaway` helper:

```js
import handle, { throwaway } from 'kefir.handle';

stream.withHandler(handle({
value: throwaway,
error: throwaway,
end: throwaway,
}));
```

Converting the [`withHandler()`](https://rpominov.github.io/kefir/#with-handler) example from the [Kefir.js](https://rpominov.github.io/kefir/) documentation.

```js
import Kefir from 'kefir';
import handle from 'kefir.handle';

var source = Kefir.sequentially(100, [0, 1, 2, 3]);
var result = source.withHandler(handle({
value(emitter, value) {
for (var i = 0; i < value; i++) {
emitter.emit(value);
}
},
end(emitter) {
emitter.emit('bye');
emitter.end();
},
}));

result.log();
```

```
> [sequentially.withHandler] 1
> [sequentially.withHandler] 2
> [sequentially.withHandler] 2
> [sequentially.withHandler] 3
> [sequentially.withHandler] 3
> [sequentially.withHandler] 3
> [sequentially.withHandler] bye
> [sequentially.withHandler]
```

```
source: ---0---1--- 2--- 3 X
result: -------•---••---••••X
1 22 333bye
```

### With ES7 `::` bind operator

```
import { handle } from 'kefir.handle';

var source = Kefir.sequentially(100, [0, 1, 2, 3]);
var result = source::handle({
value(emitter) { /* value handler */ }
})
```