iosswiftcombinecurrentvaluesubjectproperty-wrapper-published

Difference between CurrentValueSubject and @Published


So I'm digging into combine and this question came up.

Is there any real difference between using CurrentValueSubject (and setting its value using currentValueSubject.value) or using a @Published var and accessing its publisher with a $? I mean I know one returns a Subject instead of a Publisher, but the only real difference I could find is that CurrentValueSubject is way more useful because you can declare it on a protocol.

I really don't understand how @Published can be useful if we can just use PassthroughSubject, am I missing something here? Mind you, this is using UIKit, it may have other uses for SwiftUI.

Thank you.


Solution

  • @Published is just a quick way to use CurrentValueSubject a little neater. When I debug one of my apps and look at the type returned by $paramName , it's actually just a CurrentValueSubject:

    po self.$books
    ▿ Publisher
      ▿ subject : <CurrentValueSubject<Array<Book>, Never>: 0x6000034b8910>
    

    I guess one benefit of using CurrentValueSubject instead of @Published may be to allow you to use the error type?

    Note: Despite being a CurrentValueSubject right now I'd never rely on that assumption.