I have a collection of items that I need to loop through in order to determine whether or not a modal dialog should be displayed to the user, and then pause the iteration until the user provides input. The items are stored within an observable as
Observable<Array<Item>>;
.
Each item in the array needs to be checked to see if its type is already included in a Map<ItemType, string>
object. If it is not present, a modal prompting the user to enter a comment should appear, and the entered value should be saved in the map. If the type is already present, no action should be taken and the iteration should continue. Below is some pseudo code illustrating what I am trying to accomplish.
Map<ItemType, string> comments;
Observable<Array<Items>> items;
foreach (item in items) {
if(comments[item.type]) {
continue to next item;
} else {
show a modal dialog and wait for the userInput;
onModalClose -> comments[item.type] = userInput
}
}
The modal itself returns a new observable containing the user's input.
My challenge lies in figuring out how to handle waiting for the modal observable to complete before proceeding with the iteration of the observable array, the RxJs way. Using promise chains would not be difficult for me.
I have attempted several approaches but I may have become too overwhelmed by my efforts to clearly understand the solution. My most recent attempt, although likely far from ideal, is shown below.
this.items$.pipe( //Observable<Array<Item>>
map(items => items.map(i => of(i))), //Convert to an Array<Observable<Item>>
switchMap(items => {
return concat(...items).pipe(
switchMap(item => {
return this.showExtraInformationModal().pipe(
map(resultFromModal => {
// Use the result from modal
})
);
})
)
})
).subscribe();
What is the correct way to address the "Wait for user input and then continue!" situation with observables?