Best practice to handle indefinite http calls sequentially

Discussão em 'Angular' iniciado por igorjrr, Fevereiro 9, 2025.

  1. igorjrr

    igorjrr Guest

    I have a situation that I can describe being like this:

    In Angular (using version 19), I have a function A that has an array of fruits (apple, orange, etc.). Function A must call, sequentially for every fruit, function B passing the fruit as argument and wait until function B fully executes for each fruit.

    Function B will receive the fruit from function A and must call function C passing the fruit and zero as starting tree number as argument and wait until function C fully executes for each fruit and tree number.

    Function C will receive the fruit and tree number from function B and must call a web API, using HttpClient with a subscribe next, error, complete implementation, that returns true if it reached the final tree number for the fruit, or false if it should call the next tree number.

    Function B must call function C sequentially (not concurrently) for every tree number until function C returns true (meaning that there are no more trees left). Only then function B returns to function A that it completed the fruit.

    I know there is more than one way to handle this. One of the approaches I'm thinking is to return Observable from functions B and C so their callers know when they completed, meaning I would have to encapsulate the HttpClient and function C call (inside function B) inside an Observer, like this:

    functionB(fruit: string): Observable<string> {
    return new Observable<void>(observer => {
    const processTree = (treeNumber: number) => {
    this.functionC(fruit, treeNumber).subscribe({
    next: (isFinal: boolean) => {
    if (isFinal) {
    observer.next(fruit);
    observer.complete();
    } else {
    // Not the final tree – continue with the next tree number.
    processTree(treeNumber + 1);
    }
    },
    error: err => observer.error(err)
    });
    };

    processTree(0);
    });
    }


    functionC(fruit: string, treeNumber: number): Observable<boolean> {
    return new Observable<boolean>(observer => {
    this.http.get<any>(url).subscribe({
    next: response => {
    observer.next(response.final);
    if (response.final) observer.complete();
    },
    error: err => observer.error(err),
    });
    });
    }


    Would that be acceptable, is it a best practice? Or there is a more elegant way to solve this?

    I am aware of concatMap but in this case I don't have a definite amount of calls, I think it doesn't work in this case.

    Thanks for any input.

    Continue reading...

Compartilhe esta Página