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
  • Recursos adicionales
  1. Operadores
  2. Utilidad

repeat

Retorna un Observable que se resuscribe count veces al flujo fuente cuando el Observable fuente se completa

PreviousobserveOnNextrepeatWhen

Last updated 2 years ago

Signatura

Firma

repeat<T>(count: number = -1): MonoTypeOperatorFunction<T>

Parámetros

Retorna

MonoTypeOperatorFunction<T>: Un Observable que se resuscribirá count veces al flujo fuente cuando el flujo fuente se complete.

Descripción

Repite todos los valores emitidos por la fuente. Es como el operador retry, para casos que no sean de error.

De forma similar a retry, este operador repite el flujo de elementos emitidos por la fuente, para casos que no sean de error. repeat puede ser útil para crear Observables que deban tener alguna clase de patrón repetido.

Nota: repeat(0) retorna un Observable vacío y repeat() se repetirá para siempre.

Ejemplos

Repetir una petición AJAX

import { repeat } from "rxjs/operators";
import { of } from "rxjs";

const ghibliFilm$ = ajax.getJSON(
  "https://ghibliapi.herokuapp.com/films/58611129-2dbc-4a81-a72f-77ddfc1b1b49"
);

ghibliFilm$
  .pipe(
    map(({ title }) => title),
    repeat(3)
  )
  .subscribe(console.log);
// Output: My Neighbor Totoro, My Neighbor Totoro, My Neighbor Totoro

Retornar un Observable vacío

import { repeat } from "rxjs/operators";
import { of } from "rxjs";

const language$ = of("JavaScript", "TypeScript", "Go");

language$.pipe(repeat(0)).subscribe({
  next: console.log,
  complete: () => console.log("Flujo completado"),
});
// Salida: Flujo completado

Repetir un flujo de mensajes de forma infinita

import { repeat } from "rxjs/operators";
import { of } from "rxjs";

const answer$ = of("La respuesta es 42");

answer$.pipe(repeat()).subscribe(console.log);
// Salida: La respuesta es 42, La respuesta es 42, La respuesta es 42, La respuesta es 42...

Ejemplos de la documentación oficial

Repetir un flujo de mensajes

import { of } from "rxjs";
import { repeat, delay } from "rxjs/operators";

const source = of("Repetir mensaje");
const example = source.pipe(repeat(3));
example.subscribe((x) => console.log(x));

// Salida:
// Repetir mensaje
// Repetir mensaje
// Repetir mensaje

Repetir 3 valores, 2 veces

import { interval } from "rxjs";
import { repeat, take } from "rxjs/operators";

const source = interval(1000);
const example = source.pipe(take(3), repeat(2));
example.subscribe((x) => console.log(x));

// Salida: (cada segundo)
// 0
// 1
// 2
// 0
// 1
// 2

Recursos adicionales

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