Delegate pattern for actions #1007
Replies: 2 comments 2 replies
-
Great topic @rcarver! I don't use this approach for delegates, but I've started breaking my actions with subtypes like you did with The I guess the But this is a very interesting topic! Footnotes
|
Beta Was this translation helpful? Give feedback.
-
Here's another sketch of how a parent could observe a child's delegate actions more clearly. enum CountAction: DelegatingAction {
case increment
case delegate(DelegateAction)
enum DelegateAction {
case didIncrementCount(Int)
}
}
enum ParentAction {
case count(CountAction)
}
static let parentReducer = Reducer<ParentState, ParentAction, Void>.combine(
countReducer.pullback(
state: \.count,
action: /ParentAction.count,
environment: { $0 }
),
Reducer { state, action, _ in
switch action {
case .count:
return .none
}
}
.delegate(action: /ParentAction.count) { state, action, environment in
switch action {
case .didIncrementCount:
state.lastCountAt = Date()
return .none
}
}
) Since there's nothing to observe outside the delegate it could be simplified further: static let parentReducer = Reducer<ParentState, ParentAction, Void>.combine(
countReducer.pullback(
state: \.count,
action: /ParentAction.count,
environment: { $0 }
)
.delegate(action: /ParentAction.count) { state, action, environment in
switch action {
case .didIncrementCount:
state.lastCountAt = Date()
return .none
}
}
) |
Beta Was this translation helpful? Give feedback.
-
Here's an idea I've been enjoying lately, just sharing in case it's interesting to others – I've started using a kind of 'delegate' pattern to clarify which child actions are designed to be observed by a parent domain.
A common use case to close a sheet:
.tappedSaveButton
.tappedCancel
or.tappedConfirm
When this domain is composed, it gets confusing as to which action should be observed to handle tearing down the child. Consider as things evolve; perhaps the confirmation dialog is added later. There'd be nothing to tell users of this domain to change how they observe closing.
Instead, define a public 'delegate' interface that clarifies which actions should be observed, like this:
A few benefits I've found:
case .delegate:
and skip everything that it doesn't need to handle.Has anyone done something similar? Any better ways to approach this? Does the word 'delegate' capture the intent?
You really don't need any tools to use this pattern, but here's a way to clean up triggering the delegating action.
And a working example:
Beta Was this translation helpful? Give feedback.
All reactions