nalexn / clean-architecture-swiftui

SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.
MIT License
5.57k stars 671 forks source link

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

Closed zrfrank closed 4 years ago

nalexn commented 4 years ago

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 commented 4 years ago

Thanks! Really excellent explanations!