Using rxjs v6
So I have multiple variables that I want to track/observe, and when any of them change, trigger an Observable to call an API, which then updates something else based on those variables.
I thought I could maybe trigger an event on a div
to force the observable to do something, but it's not returning results based on what I want
E.g.
var a, b, c, d // if any updates, should trigger div "update" event
let obs = fromEvent(this.$refs.updater, "update")
.pipe(
switchMap(i => {return this.callAnAPI()})
)
obs.subscribe()
var update = new Event("update")
this.$refs.updater.dispatchEvent(update)
However, there is no subscribe method on the observable. I was trying to modify one of my other Observables (which works)
fromEvent(input, "keyup")
.pipe(
map(i => i.currentTarget.value),
debounceTime(delay),
distinctUntilChanged(),
switchMap(value =>
{
this.page = 1
if (ajax)
{
return ajax
}
else
{
return this.axiosAjax({
path,
method,
data: {
...data,
[term]: value
}
})
}
})
)
Based on the title of your question, I'm speculating that your custom event is just a means to an end.
If so, I don't think it's actually necessary. If you want "outside" influence (or a trigger) over an observable, use a Subject
.
For example:
const { fromEvent, merge, of, Subject } = rxjs;
const { switchMap, delay } = rxjs.operators;
// fake api
const fakeApi$ = of(Math.random()).pipe(
delay(2000),
);
// store a reference to the subject
const triggerApi$ = new Subject();
// apply behavior
const api$ = triggerApi$.pipe(
switchMap(
() => {
console.log('switching to api call');
// delegate to api call
return fakeApi$;
}
)
);
// activate (handle result)
api$.subscribe((result) => {
console.log('api result', result);
});
// some outside triggers
const fooClicks$ = fromEvent(document.getElementById('foo'), 'click');
const barClicks$ = fromEvent(document.getElementById('bar'), 'click');
const bazChanges$ = fromEvent(document.getElementById('baz'), 'change');
// combined
const updates$ = merge(fooClicks$, barClicks$, bazChanges$);
// activate
updates$.subscribe(triggerApi$);
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
<button id="foo">foo</button>
<button id="bar">bar</button>
<textarea id="baz"></textarea>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments