1

I am trying to setup a simple queue, then poll until complete style mechanism using rxjs Observables and have been struggling to figure out what I'm doing wrong.

I have the following code

siteService.queue("123")  //(1) Queues a processing task
        .pipe(
            switchMap((res) => {
                console.log("Polling for changes...");
                return timer(100, 2000)  //(2)
                    .pipe(
                        flatMap(() => {
                            console.log("Fetching Site...");
                            return siteService.get("123);  //(3)
                        }),
                        takeWhile((res: SiteResponse) => {
                             let r = res.site.site_generation_status !== 'Current';
                            console.log("Take While", r); //(4)
                            return r;
                        })
                    );
            })
        )
        .subscribe((res) => {
            console.log("Result", res);
        }, (err) => {
            console.error("Error", err);
        }, () => {
            console.log("Done")
        });

This code should queue some processing request (1) which will then set the site_generation_status of the site object to 'Queued' and will be fulfilled by some backend process which eventually updates the status to 'Current'. The idea is that the timer (2) should initially fetch the result after 100ms and then run every 2000 ms until the generation_status is current.

This code mostly works, however, the call at (3) continues to be executed after the takeWhile (4) evaluates to false

Here is some console output

Polling for changes...
Fetching Site...
Take While true
Result {site: {…}}
Fetching Site...
Take While true
Result {site: {…}}
Fetching Site...
Take While true
Result {site: {…}}
Fetching Site...
Take While false
Done
Fetching Site...
Fetching Site...
Fetching Site...
Fetching Site...

Does anyone have any ideas as to what may be causing the command at (3) to continue to be executed after the takeWhile evaluates to true and the subscription ends (indicated by 'Done' in the log output)

1 Answer 1

1

Arghh.. Gotta love figuring out the problem after 5 minutes of posting the question..

The issue was that I had imported the wrong timer which was not violently wrong enough to cause obvious issues with the code execution (perhaps a lesson for the next person).

The issue was I imported thanks to my IDE

import { timer } from "rxjs/internal/observable/timer";

but the correct import is

import { timer } from 'rxjs';

and magically now my code works as expected

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.