Documentación RxJS
  • Introducción
  • Operadores
    • Combinación
      • combineAll
      • combineLatest
      • concat
      • concatAll
      • exhaust
      • forkJoin
      • merge
      • mergeAll
      • race
      • startWith
      • switchAll
      • withLatestFrom
      • zip
    • Condicional
      • defaultIfEmpty
      • every
      • find
      • findIndex
      • isEmpty
      • sequenceEqual
    • Creación
      • ajax
      • defer
      • from
      • fromEvent
      • fromEventPattern
      • fromFetch
      • generate
      • iif
      • interval
      • of
      • range
      • throwError
      • timer
    • Gestión de Errores
      • catchError
      • retry
      • retryWhen
    • Filtración
      • audit
      • auditTime
      • debounce
      • debounceTime
      • distinct
      • distinctUntilChanged
      • distinctUntilKeyChanged
      • elementAt
      • filter
      • first
      • ignoreElements
      • last
      • sample
      • sampleTime
      • single
      • skip
      • skipLast
      • skipUntil
      • skipWhile
      • take
      • takeLast
      • takeUntil
      • takeWhile
      • throttle
      • throttleTime
    • Matemáticos y Agregación
      • count
      • max
      • min
      • reduce
    • Multidifusión
      • connect
      • multicast
      • publish
      • publishBehavior
      • publishLast
      • publishReplay
      • refCount
      • share
      • shareReplay
    • Transformación
      • buffer
      • bufferCount
      • bufferTime
      • bufferToggle
      • bufferWhen
      • concatMap
      • concatMapTo
      • exhaust
      • exhaustMap
      • expand
      • groupBy
      • map
      • mapTo
      • mergeMap
      • mergeMapTo
      • mergeScan
      • pairwise
      • partition
      • pluck
      • scan
      • switchMap
      • switchMapTo
      • window
      • windowCount
      • windowTime
      • windowToggle
      • windowWhen
    • Utilidad
      • delay
      • delayWhen
      • dematerialize
      • finalize
      • materialize
      • observeOn
      • repeat
      • repeatWhen
      • subscribeOn
      • tap
      • timeInterval
      • timeout
      • timeoutWith
      • timestamp
      • toArray
  • Conceptos
    • Observables
    • Observadores
    • Operadores
    • Schedulers
    • Sujetos
    • Suscripción
    • Testing de Canicas
  • API
    • Índice
      • ArgumentOutOfRangeError
      • bindCallback
      • bindNodeCallback
      • CompletionObserver
      • config
      • ConnectableObservable
      • EmptyError
      • ErrorObserver
      • FactoryOrValue
      • GroupedObservable
      • identity
      • InteropObservable
      • isObservable
      • MonoTypeOperatorFunction
      • NextObserver
      • noop
      • Notification
      • ObjectUnsubscribedError
      • observable
      • Observable
      • ObservableInput
      • ObservedValueOf
      • ObservedValuesFromArray
      • Observer
      • Operator
      • OperatorFunction
      • PartialObserver
      • pipe
      • scheduled
      • SchedulerAction
      • SchedulerLike
      • Subscribable
      • SubscribableOrPromise
      • Subscriber
      • Subscription
      • SubscriptionLike
      • TeardownLogic
      • TimeInterval
      • TimeoutError
      • Timestamp
      • UnaryFunction
      • Unsubscribable
      • UnsubscriptionError
      • VirtualTimeScheduler
    • ajax
      • AjaxError
      • AjaxRequest
      • AjaxResponse
      • AjaxTimeoutError
    • Schedulers
      • animationFrame
      • asap
      • async
      • queue
    • Sujetos
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
      • WebSocketSubject
    • webSocket
      • WebSocketSubjectConfig
    • Testing
  • Guías
    • Glosario
    • Importación
    • Instalación
    • Breaking Changes
      • Argumentos Array
      • Argumentos resultSelector
      • Argumentos scheduler
      • Argumentos subscribe
      • Conversión a Promesas
      • Multicasting
  • Sobre Nosotros
    • El Equipo
    • Código de Conducta
Powered by GitBook
On this page
  • Descripción
  • Ejemplos
  • Ejemplo de la documentación oficial
  • Recursos adicionales
  1. Operadores
  2. Transformación

bufferToggle

Acumula valores del Observable fuente a partir de una emisión de openings en un búfer, que se cierra cuando el Observable retornado por la función closingSelector emite

PreviousbufferTimeNextbufferWhen

Last updated 2 years ago

Signatura

Firma

bufferToggle<T, O>(openings: SubscribableOrPromise<O>, closingSelector: (value: O) => SubscribableOrPromise<any>): OperatorFunction<T, T[]>

Parámetros

Retorna

OperatorFunction<T, T[]>: Un Observable de arrays de valores almacenados.

Descripción

Almacena valores en un array. Abre el búfer cuando openings emite, y llama a la función closingSelector para obtener el Observable que indica cuándo cerrar el búfer.

Almacena valores del Observable fuente abriendo el búfer cuando el Observable openings lo indica, cerrando dicho búfer y emitiéndolo cuando el Subscribable o la Promise retornados por la función closingSelector emiten.

Ejemplos

Abrir el búfer cada cuatro segundos, durante dos segundos

import { fromEvent, interval } from "rxjs";
import { bufferToggle } from "rxjs/operators";

const number$ = interval(1000);

number$
  .pipe(bufferToggle(interval(4000), (_) => interval(2000)))
  .subscribe(console.log);
// Salida: [3, 4], [7, 8], [11, 12]...

Emitir eventos MouseEvent mientras esté pulsado el botón del mouse, hasta que dejemos de pulsarlo

import { fromEvent } from "rxjs";
import { bufferToggle } from "rxjs/operators";

const mouse$ = fromEvent<MouseEvent>(document, "mousemove");

mouse$
  .pipe(
    bufferToggle(fromEvent(document, "mousedown"), (_) =>
      fromEvent(document, "mouseup")
    )
  )
  .subscribe(console.log);
// Salida: [MouseEvent, MouseEvent, MouseEvent, MouseEvent]...

Ejemplo de la documentación oficial

Cada dos segundos, emite los eventos click de los siguientes 500 milisegundos

import { fromEvent, interval, EMPTY } from "rxjs";
import { bufferToggle } from "rxjs/operators";

const clicks = fromEvent(document, "click");
const openings = interval(1000);
const buffered = clicks.pipe(
  bufferToggle(openings, (i) => (i % 2 ? interval(500) : EMPTY))
);
buffered.subscribe((x) => console.log(x));

Recursos adicionales

StackBlitz
Documentación oficial en inglés
StackBlitz
Diagrama de canicas del operador bufferToggle
Source code