简体   繁体   中英

How to trigger a filter of a BehaviorSubject stream when fromEvent("scroll') stream publishes?

Preface: I have some incorrect procedural code with hopes, that it communicates intent. I have a feeling that an operator like flatMap or switchMap will solve this problem; however, I still haven't made the mental leap in RXJS to really understand, how or when to use these operators. So please bear with me.

Description: I have 2 streams:

  • var scrolling = Observable.fromEvent(target, 'scroll'); which correctly captures the scroll event.

  • var sampleFiltered = this.sampleElementsActiveCollection which is suppose to represent a stream of offsets that currently satisfy the rules/requirements: offset < 10 && offset > 0 . eg Elements are within 10 pixels from the top of the window.

Question: When a scroll event occurs, How do I trigger a filter on the var sampleFiltered = this.sampleElementOffsetData ? (this is currently not triggering. ) Moreover, How would I clean up nested subscribes as they are currently just to communicate intent and not working at all.

import { Directive, HostListener } from '@angular/core';
import { ScrollerElementsStoreModel } from './scroller-elements-store.model';
import 'rxjs/add/operator/filter';
import {Observable} from "rxjs";
import {BehaviorSubject} from 'rxjs/Rx';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/filter';

@Directive({
  selector: '[mh-scroll]'
})
export class MhScroll {
  lastKnownScrollPosition: number;
  ticking: boolean;
  sampleElementOffsetData: BehaviorSubject<number[]>;

  constructor(private scrollElementsStore: ScrollerElementsStoreModel) {
    this.lastKnownScrollPosition = 0;
    this.ticking = false;
    this.sampleElementOffsetData = new BehaviorSubject([100,350]);
  }


    isElementCloseToTop(target) {

      var scrolling = Observable.fromEvent(target, 'scroll'); //this works


      var scrollingSub = scrolling.subscribe(
          (x) => { // this works.

            // this section below is completely wrong; 
            // however, hopefully shows intent, that when 
            // scrolling.subscribe triggers I want to run this filter.
            var sampleFiltered = this.sampleElementOffsetData.filter((x) => {
              var offset = x + this.lastKnownScrollPosition;

              // return when element offset is within 10px.
              return offset < 10 && offset > 0 
            },this);


            var sub =  sampleFiltered.subscribe(
              (y) => {
               // Update DOM.
              }
            )
          },
          (err) => {
            console.log('Error: %s', err);
          },
          () => {
            console.log('Completed');
          });

      this.ticking = false;
    }


    @HostListener('window:scroll', ['$event.target'])
    triggeredScroll(target) {
      this.lastKnownScrollPosition = window.scrollY;

      if (!this.ticking) {
        window.requestAnimationFrame(this.isElementCloseToTop.bind(this, target));
      }

      this.ticking = true;
    }
}

There were 2 problems with my code: 1) there was a type error in the BehaviorSubject Observable.filter will only iterate over Observables NOT an Observables values.

2) I was able to clean this up using the operator .mergeMap TL;DR: Map values from source to inner observable, merge output

var scrolling = Observable.fromEvent(target, 'scroll')
          .mergeMap(event => this.scrollElementsStore.elementUpdated.filter((event) => {
            var offset = event + this.lastKnownScrollPosition;
            console.log(event);
            return offset < 10 && offset > 0;
          }
        )).subscribe((x)=>{
          console.log(x, 'asdfasdf');
        })

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