Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Difference between @Published and CurrentValueSubject #138

Open
mycroftcanner opened this issue Nov 29, 2019 · 0 comments
Open

Difference between @Published and CurrentValueSubject #138

mycroftcanner opened this issue Nov 29, 2019 · 0 comments
Labels
enhancement New feature or request

Comments

@mycroftcanner
Copy link

mycroftcanner commented Nov 29, 2019

People seems to be confused about the differences between a @published wrapped property and a CurrentValueSubject.

CurrentValueSubject is a value, a publisher and a subscriber all in one.

Sadly it doesn’t fire objectWillChange.send() when used inside an ObservableObject.

You can specify an error type.

@Published is a property wrapper, thus:

  • It is not yet supported in top-level code.
  • It is not supported in a protocol declaration.
  • It can only be used within a class.

@Published automatically fires objectWillChange.send() when used inside an ObservableObject.

Xcode will emit a warning if your try to publish to @Published wrapped property from a background queue. Probably because objectWillChange.send() must be called from the main thread.

The error type of its publisher is Never

My biggest beef against @Published is that it can’t behave as a subscriber and setting up Combine pipelines requires additional plumbing compared to a Current Value Subject.

We can declare a @Published property inside a protocol. It is kinda ugly.

protocol TestProtocol {
    var isEnabled: Bool { get }
    var isEnabledPublished: Published<Bool> { get }
    var isEnabledPublisher: Published<Bool>.Publisher { get }
}

class Test: ObservableObject, TestProtocol {
    @Published var isEnabled: Bool = false
    var isEnabledPublished: Published<Bool> { _isEnabled }
    var isEnabledPublisher: Published<Bool>.Publisher { $isEnabled }
@heckj heckj added the enhancement New feature or request label Dec 1, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants