0
votes

Is there any reason to emit an event on a subject with startWith

let publishedSubject1 = PublishedSubject<Void>()
publishedSubject1
    .startWith(Void())
    .subscribe()
    .dispose(by: bag)

vs. just using .onNext

let publishedSubject2 = PublishedSubject<Void>()
publisedSubject2
    .subscribe()
    .dispose(by: bag)
publishedSubject2.onNext(Void())

Is this just one of those Rx tricks to do the same thing just in different stylistic ways in the same vein that .map is used to hide nested subscribes by moving the subscribe inside the map operator? I've looked at the code here: https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observables/StartWith.swift and it just seems like another trick. Is there a functional reason to use .startWith instead of just .onNext?

1

1 Answers

0
votes

[Subjects] are the "mutable variables" of the Rx world and in most cases you do not need them.Typically a solution with Create or the other operators allows you to just wire up continuations without adding extra state.

-- Erik Meijer

Using a more declarative solution gives you an opportunity to not use Subjects at all. To put it another way, using a Subject and manually calling onNext isn't much different than just calling a function with a parameter, so if you insist on using Subjects even if you don't have to, then why use Rx at all?