Try to search your question here, if you can't find : Ask Any Question Now ?

How to create an observable in RxJS which waits for 2 observables ( in sequence) , then acts , and then waits for those 2 again in sequendce

HomeCategory: stackoverflowHow to create an observable in RxJS which waits for 2 observables ( in sequence) , then acts , and then waits for those 2 again in sequendce
sourav asked 2 weeks ago

I’m struggling with a specific scenario for which I was hoping to use RxJS :

There are two observables which should trigger in sequence for a value to be registered :

  1. An observable representing a user pressing a button

  2. An observable representing a device returning it’s next value

After the user presses the button, it should wait until the device returns it’s next value, then this value should be captured and processed. After that, it should again wait for the same sequence of events.

I found that it works once if I use concat, and I complete the observables upon receiving the button action and the device’s value.

However, after the observables complete I can’t use them anymore for subsequent actions.

I also found that I could use zip, which would trigger after both observables return their next() , but then the order isn’t guaranteed ( it won’t return the next value after the button was pressed, it will emit the value that was emitted in the meantime).

What would be the best-practice solution for this case ?

import { Observable, Subject, forkJoin } from 'rxjs';
import { concat, repeat, switchMap } from 'rxjs/operators';

let user: Subject<any> = new Subject<any>();
let device: Subject<number> = new Subject<number>();

user.pipe(concat(device)).subscribe(() => {
    console.log("both called");
});


setInterval(() => {
    setTimeout(() => {
        user.complete();
        console.log("user action executed");
    }, 2000);

    setTimeout(() => {
        device.next(new Date().getSeconds());
        console.log("device value sent");
        device.complete();
    }, 5000);
}, 10000);
1 Answers
Best Answer
Mannu answered 2 weeks ago
Your Answer

7 + 19 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com