Home > OS >  Combining Observables with only some completing and no initial values
Combining Observables with only some completing and no initial values

Time:04-01

I have two Observables that collect input from the dom:

private inputSource = new BehaviorSubject(null);
const selctionSource = fromEvent(this.input.nativeElement,'keyup')

Then i want to combine these two

const combined = merge( selctionSource, this.inputSource.pipe(skip(1)) )

Now, i need to get the input values out of the observables and assign them to a data Object, which is then handed down to the Server for Server side filtering a dat set of a mat table

combined
     .pipe(
        debounceTime(150),
        tap(() => {
          const typesArray: string[] = []
          typesArray.push(this.inputSource.value.value)

          const data: ServerFilter = {
          name : this.input.nativeElement.value,
          types : typesArray
          }

         this.filterService.applyFilter(data)
        
        })
    )
    .subscribe();

The Observable must be somehow combined, because the user must be able to filter based on multiple inputs (That works)

There cant be a start value for each observable, because that would lead to an emit with unknown values to the server, resulting in no output of the data table. (I took care of that already)

Problem: As described in the documentation, both combineLatest and merge only emit once all observables complete.

I need the data object to be sent, even if only one observable emits a value. The solution that exists on stackOverflow recommends using startwith values, which i cant use.

CodePudding user response:

You might be overcomplicating this.

There cant be a start value for each observable

Then use a Subject instead of BehaviourSubject.

I need the data object to be sent, even if only one observable emits a value

Handle each subscription separately. No need to merge the observables if you don't want to wait for both of them.

CodePudding user response:

You can use mergeWith instead merge.

https://rxjs.dev/api/operators/mergeWith

private inputSource = new Subject();
const selectionSource = fromEvent(this.input.nativeElement,'keyup');
selectionSource.pipe(mergeWith(inputSource)).subscribe(...);

You can use behaviorSubject if you want to trigger the filter at starting. Also you can use Subject and trigger your filter manually in the ngOnInit method.

  • Related