I have old-style library with 4 asynchronous functions - lets call them libA
, libB
, libC
, libD
(the running time of each is unknown/random) - when they finish they call my callback
I write loadString
function which return observable (which should contains results of each callback function - I use string here for simplicity but it can be array of results) but it gives wrong result "AADDDDD". The expected result is "AADDDDDCCCCBBB". How to do it right using rxjs?
function loadString() {
let result = '';
return Observable.create(observer =>{
libA( n=> { result+='A'.repeat(n) });
libB( n=> { result+='B'.repeat(n) });
libC( n=> { result+='C'.repeat(n) });
libD( n=> {
result+='D'.repeat(n);
observer.next(result);
});
})
}
Below there is working snippet which you can copy to your answer and develop loadString function
// SET-UP
const { of, Observable } = rxjs;
const { map, switchMap, delay } = rxjs.operators;
// simulated lib function - not change this (the times are random)
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); }
// QUESTION: how to write below function body using rxjs?
function loadString() {
let result = '';
return Observable.create(observer =>{
libA( n=> { result+='A'.repeat(n) });
libB( n=> { result+='B'.repeat(n) });
libC( n=> { result+='C'.repeat(n) });
libD( n=> {
result+='D'.repeat(n);
observer.next(result);
});
})
}
// TEST
let s = loadString().subscribe(str=> {
console.log(str); // wrong result: I expected "AADDDDDCCCCBBB" value
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.min.js" integrity="sha256-85uCh8dPb35sH3WK435rtYUKALbcvEQFC65eg+raeuc=" crossorigin="anonymous"></script>
UPDAE
I would like to not run lib functions in sequential way but parallel (they send some requests to API...)