[英]How to properly chain RxJS observables together with a for loop?
[英]Best way to chain Observables using RxJs in React
在這種情況下,最好的方法是鏈接 Observables 並在所有訂閱完成后分派SEARCH_QUERY_COMPLETE
操作? 我注意到forkJoin
已被棄用...
const launchSearchQuery = () => {
mainDispatch({
type: ActionTypes.LAUNCH_SEARCH_QUERY,
});
if (mainState.searchSection.searchQuery !== "") {
// get order details
orderDetailRepository.getOrderDetails(mainState.searchSection.searchQuery).subscribe((response) => {
searchResultCards.push(mapSearchResultCard(response, DashboardSectionTitles.ORDER_DETAILS));
});
// get customer details
customerDetailRepository.getCustomerDetails(mainState.searchSection.searchQuery).subscribe((response) => {
searchResultCards.push(mapSearchResultCard(response, DashboardSectionTitles.CUSTOMER_DETAILS));
});
// get equipment details
equipmentDetailRepository.getEquipmentDetails(mainState.searchSection.searchQuery).subscribe((response) => {
searchResultCards.push(mapSearchResultCard(response, DashboardSectionTitles.EQUIPMENT_DETAILS));
});
// get equipment return details
equipmentReturnDetailRepository
.getEquipmentReturnDetails(mainState.searchSection.searchQuery)
.subscribe((response) => {
searchResultCards.push(mapSearchResultCard(response, DashboardSectionTitles.EQUIPMENT_RETURN_DETAILS));
});
}
// !!! only execute this when all subscriptions are completed !!!
mainDispatch({
type: ActionTypes.SEARCH_QUERY_COMPLETE,
payload: searchResultCards,
});
};
這是getOrderDetails
的藍圖
export interface IOrderDetailRepository {
getOrderDetails: (query: string) => Observable<IOrderDetail[]>;
}
您可以像這樣使用forkJoin
-
const launchSearchQuery = () => {
mainDispatch({
type: ActionTypes.LAUNCH_SEARCH_QUERY,
});
if (mainState.searchSection.searchQuery !== "") {
forkJoin([
// get order details
orderDetailRepository.getOrderDetails(mainState.searchSection.searchQuery),
// get customer details
customerDetailRepository.getCustomerDetails(mainState.searchSection.searchQuery),
// get equipment details
equipmentDetailRepository.getEquipmentDetails(mainState.searchSection.searchQuery),
// get equipment return details
equipmentReturnDetailRepository.getEquipmentReturnDetails(mainState.searchSection.searchQuery)
]).subscribe(([orderDetails, customerDetails, equipMentDetails, equimentReturnDetails]) => {
searchResultCards.push(mapSearchResultCard(orderDetails, DashboardSectionTitles.ORDER_DETAILS));
searchResultCards.push(mapSearchResultCard(customerDetails, DashboardSectionTitles.CUSTOMER_DETAILS));
searchResultCards.push(mapSearchResultCard(equipMentDetails, DashboardSectionTitles.EQUIPMENT_DETAILS));
searchResultCards.push(mapSearchResultCard(equimentReturnDetails, DashboardSectionTitles.EQUIPMENT_RETURN_DETAILS));
// !!! only execute this when all subscriptions are completed !!!
mainDispatch({
type: ActionTypes.SEARCH_QUERY_COMPLETE,
payload: searchResultCards,
});
});
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.