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

Question: Why would the AnyPublisher be used everywhere? #32

Closed
zrfrank opened this issue Jun 21, 2020 · 2 comments
Closed

Question: Why would the AnyPublisher be used everywhere? #32

zrfrank opened this issue Jun 21, 2020 · 2 comments

Comments

@zrfrank
Copy link

zrfrank commented Jun 21, 2020

No description provided.

@nalexn
Copy link
Owner

nalexn commented Jun 21, 2020

Hey @zrfrank

Publishers in Combine maintain type information as you chain them. In the following example, the publisher variable will have the type Publishers.Debounce<Publishers.Delay<Just<Int>, RunLoop>, RunLoop>:

let publisher = Just<Int>(10)
    .delay(for: .seconds(1), scheduler: RunLoop.main)
    .debounce(for: .seconds(1), scheduler: RunLoop.main)

So if we need to return this value from a function, we'd have to specify the full type information as the return type of the function. This would be crazy inconvenient and would lead to tight coupling between the function implementation and the consumers of this function: every time you change this chain of operators (even by swapping delay and debounce), the resulting type changes, so you'll have to update not only the public function's declaration but also all the places in your app calling it.

Just the same problem exists for SwiftUI views: the resulting view type might be insanely long for exposing this as the return type. That's why in Swift 5 there is some keyword, which maintains the entire static type information for the compiler but obscures it for the human.

We could have used some keyword approach with publishers as well, but:

  1. some does not allow you to specify the associated parameters. SwiftUI views do not have those, while publishers have Value and Error
  2. Maintaining the type information is essential for SwiftUI views: this allows the drawing engine to perform the hierarchy diffing in a faster manner. Publishers don't require anything like that, so type information can be safely erased.

I hope my explanation makes sense - let me know if any clarification is needed.

@zrfrank
Copy link
Author

zrfrank commented Jun 22, 2020

Thanks! Really excellent explanations!

@zrfrank zrfrank closed this as completed Jun 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants