I have following scenario - 4 callback functions A,B,C,D which are called form old-style like library (which use some API requests inside so execution time is unknown/random but proper order of results (by finished task time) is important for me) - and I want to synchronise data which they return to one obserwable result string using rxjs.
function getData() {
// --- BELOW Part can be EDIT ---
let obs = new ReplaySubject(1); // this is example you can use an type
function A(n) {
let r= 'A'.repeat(n);
}
function B(n) {
let r= 'B'.repeat(n);
}
function C(n) {
let r= 'C'.repeat(n);
}
function D(n) {
let r= 'D'.repeat(n);
obs.next(r);
}
// --- BELOW Part can NOT be edit ---
runLib(A,B,C,D)
return obs
}
In below snippet value of finalResult
is DDDDD
which is wrong. Proper value of finalResult
string should be AADDDDDCCCCBBB
.
// SET-UP - NOT EDIT Below code
const { of, Observable, ReplaySubject } = rxjs;
const { map, switchMap, delay } = rxjs.operators; // example
// simulated lib functions
function libA(callback) { setTimeout( _=>callback(2), 1000); }
function libB(callback) { setTimeout( _=>callback(3), 3000); }
function libC(callback) { setTimeout( _=>callback(4), 2000); }
function libD(callback) { setTimeout( _=>callback(5), 1500); }
function runLib(cA,cB,cC,cD) {
libA( cA ); libB( cB ); libC( cC ); libD( cD );
}
getData().subscribe(finalResult => {
console.log(finalResult) // The result is WRONG here!
}, e=>{}, _=> console.log('finished - unsubscribed'));
function getData() {
// --- BELOW Part can be EDIT ---
let obs = new ReplaySubject(1); // this is example, you can use diffrend observale kind
function A(n) {
let r= 'A'.repeat(n);
}
function B(n) {
let r= 'B'.repeat(n);
}
function C(n) {
let r= 'C'.repeat(n);
}
function D(n) {
let r= 'D'.repeat(n);
obs.next(r);
}
// --- BELOW Part can NOT be edit ---
runLib(A,B,C,D)
return obs
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.min.js" integrity="sha256-85uCh8dPb35sH3WK435rtYUKALbcvEQFC65eg+raeuc=" crossorigin="anonymous"></script>
In snippet I mark code inside getData()
which can be edit in solution (may be it looks little awkward but this is exactly what I need) (you can also find there finalResult
but not edit that part of code). It is possible? How to do it?