Created
May 29, 2019 19:19
-
-
Save kievsash/1629f1961a9ff9eac5cbe87a9e21bd91 to your computer and use it in GitHub Desktop.
forkJoin with percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let Rx = window.Rx = window['rxjs']; | |
let {forkJoin, Subject, merge, of} = Rx; | |
let {ajax} = Rx.ajax; | |
let {map, filter, tap, takeLast, scan, startWith} = Rx.operators; | |
console.clear(); | |
function forkJoinTransparent(arrayOfObservables) { | |
const emptyArray = Array.from(Array(arrayOfObservables.length)); | |
const initialValue = {data:emptyArray, percentage: 0}; | |
const modilefiedObservablesList = arrayOfObservables.map( | |
(item, index) => item.pipe( | |
takeLast(1), | |
map(data => ({data: data, index})), | |
) | |
); | |
return merge(...modilefiedObservablesList).pipe( | |
startWith(initialValue), | |
scan((acc, next) => { | |
const newAcc = {data: [...acc.data], percentage: acc.percentage}; | |
newAcc.data[next.index] = next.data; | |
const definedValues = newAcc.data.filter(x => !!x) | |
newAcc.percentage = definedValues.length * 100/ newAcc.data.length; | |
return newAcc; | |
}, initialValue) | |
) | |
} | |
const getUserDetails = userIdsList => { | |
const arrayOfObservables = userIdsList.map(userId => | |
ajax('https://jsonplaceholder.typicode.com/comments/' + userId) | |
) | |
return forkJoinTransparent(arrayOfObservables) | |
} | |
const result$ = getUserDetails([1, 2, 15]); | |
result$.pipe( | |
tap((data) => console.log('percentage: ', data)), | |
filter(data => data.percentage === 100) | |
) | |
.subscribe((data) => console.log('final value: ', data.data)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment