Engineering

Which should we use forever or whileConnected of ShareReplay?

shareReplay of RxSwift has 2 types of sharing-scope.

  • whileConnected
  • forever

So, I've tried both sharing scopes.

shareReplay makes Observable Stateful.

The sharing-scopes indicate stateful that how long is it.

import RxSwift

print(".whileConnected, if it has subscribers that are subscribing forever")

do {
  let subject = PublishSubject<Int>()

  let s = subject.share(replay: 1, scope: .whileConnected)

  s.subscribe()
  s.debug().take(1).subscribe()

  subject.onNext(1)

  s.debug().subscribe()
}

print(".whileConnected, if all subscribes has been disposed before adding a new subscriber")

do {
  let subject = PublishSubject<Int>()

  let s = subject.share(replay: 1, scope: .whileConnected)

  s.debug().take(1).subscribe()

  subject.onNext(1)

  s.debug().subscribe()
}

print(".forever")

do {
  let subject = PublishSubject<Int>()

  let s = subject.share(replay: 1, scope: .forever)

  s.debug().take(1).subscribe()

  subject.onNext(1)

  s.debug().subscribe()
}

Result

.whileConnected, if it has subscribers that are subscribing forever
=> subscribed
=> Event next(1)
=> isDisposed
=> subscribed
=> Event next(1)

.whileConnected, if all subscribes has been disposed before adding a new subscriber
=> subscribed
=> Event next(1)
=> isDisposed
=> subscribed

.forever
=> subscribed
=> Event next(1)
=> isDisposed
=> subscribed
=> Event next(1)