2.0.0 • Published 5 years ago
intent-rxjs v2.0.0
Intent-rxjs
Create convevient handlers which are both callable and observable at the same time
Examples
Basic usage
const handler = intent(
pluck('target', 'value'),
map(normalize),
)
const field = document.getElementById('field')
field.addEventListener('input', handler)
from(handler).subscribe(logResult)
The same code using Subject
(for comparison):
const handler = new Subject()
const result = handler.pipe(
pluck('target', 'value'),
map(normalize),
)
const field = document.getElementById('field')
field.addEventListener('input', handler.next.bind(handler))
result.subscribe(logResult)
intent
helper utilizes Subject
internally and automatically applies share()
operator after all other operators in pipeline.
Counter handlers
const increment = intent(mapTo(1))
const decrement = intent(mapTo(-1))
const reset = intent(mapTo(0))
const values = merge(increment, decrement, reset)
values
.pipe(scan((count, value) => count + value, 0))
.subscribe(log)
increment()
// logs 1
increment()
// logs 2
increment()
// logs 3
decrement()
// logs 2
reset()
// logs 0
Hypothetic field store handlers:
const change = intent(map(normalize))
const validate = intent(mapTo({ validators }))
field.on(change, handleChange)
field.on(validate, handleValidation)
// ...later in UI:
<input onChange={change} onBlur={validate} />
Handle request:
const resourceUrl = 'https://jsonplaceholder.typicode.com/todos'
const createFetchTodoRequest = id => fetch(`resourceUrl/${id}`).then(response => response.json())
const fetchTodo = intent(exhaustMap(createFetchTodoRequest))
from(fetchUser).subscribe({
next: response => console.log(response),
error: error => console.error(error),
})
fetchTodo(1)