Search code examples
rxjsreactive-programming

how to convert an Array to a hot Observable


so I have an array that will change over time in size and would like to convert to a hot stream.

tried with no luck:

const array = [10, 20, 30];
        const result = from(array, asyncScheduler);
        result.subscribe(x => {
            console.log(x);
        });
        setTimeout(() => {
            array.push('waiting for me');
        }, 6000);

as 'waiting for me' never gets consoled after 6 sec. tried also share() with no avail

thanks


Solution

  • You can do this with a subject !

    const subject$ = new Subject();
    subject$.subscribe((x) => {
      console.log(x);
    });
    
    [10, 20, 30].forEach((v) => subject$.next(v));
    
    setTimeout(() => {
      subject$.next('waiting for me');
    }, 6000);
    

    NB: You need to subscribe before pushing, because the values will be sent synchronously in the particular case.


    or you can also merge 2 streams :

    const subject$ = new Subject();
    
    const array = [10, 20, 30];
    const result = from(array);
    
    setTimeout(() => {
      subject$.next('waiting for me');
    }, 6000);
    
    
    merge(result, subject$).subscribe((x) => {
      console.log(x);
    });