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. Multidifusión

publishBehavior

Comparte el Observable fuente, permitiendo proporcionar un valor por defecto

PreviouspublishNextpublishLast

Last updated 2 years ago

💡 publishBehavior es equivalente a multicast(() => new BehaviorSubject())

Signatura

Firma

publishBehavior<T>(value: T): UnaryFunction<Observable<T>, ConnectableObservable<T>>

Parámetros

Retorna

UnaryFunction<Observable<T>, ConnectableObservable<T>>

Descripción

Comparte el Observable fuente, permitiendo proporcionar un valor por defecto, ya que utiliza un BehaviorSubject internamente.

Retorna un ConnectableObservable, que es un Observable que espera a que se haga una llamada a su método connect antes de empezar a emitir valores a sus Observadores. En el caso de que no se llame a connect, el Observable fuente no emitirá ningún valor.

💡 Para evitar tener que llamar a connect manualmente, se puede utilizar el .

Ejemplos

Compartir el Observable fuente, proporcionando un valor inicial de -1

import { ConnectableObservable, interval, timer } from "rxjs";
import { publishBehavior, tap, take } from "rxjs/operators";

// number$ no empezará a emitir valores hasta que se haga una llamada a connect
const number$ = interval(1000).pipe(take(4));

const multicasted$ = number$.pipe(
  tap(() =>
    console.log("Fuente compartida, efecto secundario se ejecuta una sola vez")
  ),
  publishBehavior(-1)
) as ConnectableObservable<number>;

// Llamando a connect tras 3 segundos
timer(3000)
  .pipe(tap(() => multicasted$.connect()))
  .subscribe();

multicasted$.subscribe((val) => console.log(`Observador 1: ${val}`));
multicasted$.subscribe((val) => console.log(`Observador 2: ${val}`));

/* Salida:
Observador 1: -1, 
Observador 2: -1,
(3s)
Fuente compartida, efecto secundario se ejecuta una sola vez,
Observador 1: 0, 
Observador 2: 0,
(1s)
Fuente compartida, efecto secundario se ejecuta una sola vez,
Observador 1: 1,
Observador 2: 1,
...
*/

Recursos adicionales

operador refCount
StackBlitz
Documentación oficial en inglés
Source code