occimort occimort - 1 year ago 85
Javascript Question

map multiple callback returns into observable using RxJs

I'm currently beggining with RxJs and trying to define modules returning observables. (each module works as a blackbox and only exposes its observables).
my main problem is due to the third party library I'm using : UWA :
All my dom elements are generated from UWA objects and trigger UWA "events".
BTW I want to map those custom events to observables.
here is a part of the event data structure :

tabBar = *somecode*...{
....
onEndEditTab: function (callback) {
return this.modelEvent.subscribe({
event: endEditTabEvent
}, callback);
},....
}


Here is my current code :

const tabBar = new tabBar();
tabBar.inject(domContainer);
const observer={
next: (t) =>{
const oldValue=t.target.textContent;
const cbObservable = Rx.Observable.bindCallback(tabBar.onEndEditTab);
//a new cbObservable is created at each dblclick event
// (due to bindCallBack property which is to retern only one time.
cbObservable .call(tabBar).subscribe(
(v) => {
console.log({oldLabel:oldValue,newLabel:v[0].button.label});
}
);
Rx.Observable.fromEvent(tabBar, 'dblclick').subscribe(observer);


This code works and log the old and new value each time a tab label is edited.
But currently what I want instead of just printing this is to aggregate all those results into a new Observable stream.
using marble diagram :

dblclick : ----(1)----(2)---....(n)->


(where there is an unknown number n of dblclick...)
is mapped to :

cbObservable : ----(1:{old,new})--|
----(2:{old,new})--|
....
----(n:{old,new})--|


And what I currently want is :

outputStream : ----(1:{old,new})---(2:{old,new})--...(n:{old,new})--->


where outputStream is an hot observable;
is there a way of doing that with all constraints described above ?
thank you !

Answer Source

try to use switchMap

Rx.Observable.fromEvent(tabBar, 'dblclick').switchMap(() => {
    const oldValue=t.target.textContent;
    return Rx.Observable.bindCallback(tabBar.onEndEditTab).map((v) => {
       return {old: oldValue, new: v[0]}
    });
})

or something like this, then make single subscribtion to resulting observable

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download