问题
I have an array of contacts and would like to perform an API calls for each object in the contacts array. I have tried to loop over each item and make the call to fetchJson$, however, I realise that this approach is incorrect.
What is the correct way to do this with RXJS Redux Observables?
Also, this is pseudo code for the purpose of this question so please ignore any syntax errors.
export const createPost = (action$, store) => (
action$.ofType(UPDATE_USER_CONTACTS)
.switchMap(() => {
const state = store.getState();
const userToken = getUserToken(state);
const userId = getuserId(state);
const listOfContacts = getListUserContacts(state);
return Observable.concat(
// 1. show loading
Observable.of(showSpinner()),
// 2. set the timer
Observable.defer(() => {
const contacts = [
{
id: '123',
name: 'Paul',
phoneNumber: '000-000-00'
},
{
id: '098',
name: 'Sarah',
phoneNumber: '111-111-11'
},
]
contacts.forEach((contact) => {
return fetchJson$('PUT', `${API_URL}/users/${userId}/user_contacts/${contact.id}`, userToken, {
id: contact.id,
name: contact.name,
phoneNumber: contact.phoneNumber,
})
}, false)
.flatMap(() => (
Observable.of(
reset(),
notification({
icon: 'm-timers',
text: '<b>Good - worked</b>.',
}),
)
))
.catch(({ response }) => {
const responseArray = [];
if (response) {
console.log(response, 'there was a response')
}
return Observable.of(...responseArray);
});
}),
Observable.defer(() => {
// perform another action here
},
// 4. hide loading
Observable.of(hideSpinner()),
);
})
);
回答1:
I think you are looking for forkJoin:
signature: forkJoin(...args, selector : function): Observable . When all observables complete, emit the last emitted value from each.
const contacts = [
{
id: '123',
name: 'Paul',
phoneNumber: '000-000-00'
},
{
id: '098',
name: 'Sarah',
phoneNumber: '111-111-11'
},
];
Observable.forkJoin(
contacts.map((contact) => {
return fetchJson$('PUT', `${API_URL}/users/${userId}/user_contacts/${contact.id}`, userToken, {
id: contact.id,
name: contact.name,
phoneNumber: contact.phoneNumber,
})
}
)
);
来源:https://stackoverflow.com/questions/52169232/rxjs-redux-observable-perform-multiple-api-calls