简体   繁体   中英

timeout() operator not working in pipe Rxjs subject

I have an Issue with timeout operator in subject.

my problem look like sample above, but I got all of source,

response: observable: 1 observable: 2

url: https://stackblitz.com/edit/ou5yp1?file=index.ts

import { Subject, from,Observable } from 'rxjs';
import {timeout} from 'rxjs/operators';

const subject = new Subject();
 subject.subscribe({
  next: (v) => console.log(`observer: ${v}`),
   error: (e) => console.log(`There is an Error ${e}`)
  });
subject.pipe(timeout(2000));

const observable = new Observable( sub=> {
 sub.next( 1);
 setTimeout(()=> {
 sub.next(2)
 },5000)
})
observable.subscribe(subject); 

You have subscribed to wrong observable.

subject.pipe(timeout(2000));

The above line does not apply to subject itself, but instead returns a new observable which has 2 seconds timeout. So you should subscribe to this returned observable instead of subject itself. So your code should be:

subject.pipe(timeout(2000)).subscribe({
  next: (v) => console.log(`observer: ${v}`),
  error: (e) => console.log(`There is an Error ${e}`)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM