Swift / Apple Development Chat

Nycturne

Site Champ
Vaccinated
Posts
365
Reaction score
381
Could it be that some of this 'missing parts' of the API is just Apple trying to steer developers to certain architectures / out of some patterns? Kind of an extreme example, but I remember people complaining about how you can't create a ViewModel in a parent view and set it as a @StateObject in a child view elegantly (see this SO post). After watching some of the SwiftUI talks (specially, Demystify SwiftUI), I feel like trying to do something like that is just fighting the system (if you want SwiftUI to persist that @StateObject between view inits, you shouldn't also want to initialize it every time the view body of the parent is executed).

I wouldn’t be surprised if that’s the case. I need to fix some that StateObject nonsense in my own code as well, so there are traps, sadly. It just hasn’t been a priority until I can get some other areas cleaned up.

That said, my wrapper is in the same vein as @Published, but simpler and more suitable for model objects that want or need to publish from background threads. It is really syntactic sugar to reduce the amount of boilerplate needed to use CurrentValueSubject in model objects and make the code a hair cleaner, but it isn’t a huge win unless you are doing a lot of custom model objects or actors.

Swift:
// Using CurrentValueSubject directly
// You need to manage making the publisher accessible yourself and guard the Subject.
private var state: CurrentValueSubject<MyStateStruct, Never>
public var statePublisher: AnyPublisher<MyStateStruct, Never> { state.eraseToAnyPublisher() }
// Modify by changing value in the value subject
state.value = .init(/* New State */)
    
// Using Property Wrapper
// $state is the type-erased publisher, similar to @Published
@ValueSubject private(set) var state: MyStateStruct
// Modify like any other property:
state = .init(/* New State */)

YES! That's the exact same feeling I had with VIPER codebases. Everything is very compartimentalized and that should be a positive thing, but trying to understand the app flow as a first-timer is an absolute nightmare because you have to hunt down every affected piece of code throughout all the codebase. If the app also had network calls or any other completion handler heavy user, code could become almost undecipherable. Additionally, as the number of affected files grows, it becomes harder to keep everything inside your 'mental model' of the code.

And I think the thing is, this is more of a “how are files placed on disk” problem, than a fundamental issue with the approach. Just give me a folder called “Authentication” that includes the state, reducers, etc and let me see the whole component. Then we can compose the different components into the global store.
 
Top Bottom