简体   繁体   中英

Which rxjs operator is more suitable to get value from two observables although only one not emitted?

I have two FormControl :

  criteria = new FormControl('');
  term = new FormControl('');

I using combine to get the last value emitted from those values.

  @Output() change = combineLatest([this.term.valueChanges, this.criteria.valueChanges]).pipe(
    map((r) => {
      return r.join(' ');
    })
  );

The problem is only when two values are emitted then change is emit.

Which rxjs operator more suitable to trigger the change when one of the observables are emitted or both?

Codesandbox

Use something like this. You can don't use messages from valueChanges.

merge(this.term.valueChanges, this.criteria.valueChanges).pipe(
    map(() => {
      return [this.term.value, this.criteria.value].join();
    })
  );

You can stick a startsWith in to make sure they emit before keystroke

 const { of, combineLatest } = rxjs; const { startWith, delay } = rxjs.operators; combineLatest([ of(1).pipe(startWith(0), delay(1000)), of(2).pipe(startWith(0), delay(500)) ]).subscribe(val => { console.log(val); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js"></script>

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