close

How to make one Observable sequence wait for another to complete before emitting?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to make one Observable sequence wait for another to complete before emitting? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to make one Observable sequence wait for another to complete before emitting ?

  1. How to make one Observable sequence wait for another to complete before emitting ?

    make one Observable sequence wait for another to complete before emitting If you want to make sure that the order of execution is retained you can use flatMap as the following example

  2. make one Observable sequence wait for another to complete before emitting

    make one Observable sequence wait for another to complete before emitting If you want to make sure that the order of execution is retained you can use flatMap as the following example

Method 1

A couple ways I can think of

import {take, publish} from 'rxjs/operators'
import {concat} from 'rxjs'

//Method one

var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1));
concat(one, two).subscribe(function() {/*do something */});

//Method two, if they need to be separate for some reason
var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1), publish());
two.subscribe(function(){/*do something */});
one.subscribe(function(){/*do something */}, null, two.connect.bind(two));

Method 2

If you want to make sure that the order of execution is retained you can use flatMap as the following example

const first = Rx.Observable.of(1).delay(1000).do(i => console.log(i));
const second = Rx.Observable.of(11).delay(500).do(i => console.log(i));
const third = Rx.Observable.of(111).do(i => console.log(i));

first
  .flatMap(() => second)
  .flatMap(() => third)
  .subscribe(()=> console.log('finished'));

The outcome would be:

"1"
"11"
"111"
"finished"

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment