rxjssubject

Wait async subscriptions when I emit next value


I have the next example

import { Subject } from "rxjs";

const subject = new Subject();

subject.subscribe(() => new Promise(res => {
  setTimeout(() => console.log('!! 1'), 500);
}))

subject.subscribe(() => new Promise(res => {
  setTimeout(() => console.log('!! 2'), 1000);
}))

console.log('>>> START')
subject.next();
console.log('<<< FINISH')

Console looks like

>>> START
<<< FINISH
!! 1
!! 2

I want the following behavious

>>> START
!! 1
!! 2
<<< FINISH

Can I reach expected behaviour or I should to use another aproach?


Solution

  • Ok so, this should work. I just forced the behavior of the Observables. To be clear, observables are async javascript and need to share values in async mode so that you can 'emit' a new value through a subject and all the observables can see that value while doing some other tasks. This code do exactly what you asked for but it makes no sense to emit a value and await for that value in the same place and moment, to achieve that you should probably think about another way of coding this module.

    Said that, i've tested this snippet and it works, hope this will help

    import { Subject } from "rxjs";
    const subject = new Subject();
    
    async function nextValue(value) {
        return new Promise((resolve, reject) => {
            subject.subscribe(subValue => {
                setTimeout(() => {
                     console.log(subValue);
                     resolve();
                }, 500);
            }, err => reject(err));
            subject.next(value);
        });
    }    
    
    (async () => {
        console.log('>>> START');
        await nextValue('myValue');
        console.log('<<< FINISH');
    })();