This includes Command
and Subscription
which are excluded for simplicity in v1.
Differences from v1
- elements
- add
Command
- add
Subscription
- add
- behavior
- save current value in UserDefaults using
Command
- load value from UserDefaults using
Command
- observe app state change (entered background/foreground) using
Subscription
, then save/load value
- save current value in UserDefaults using
Command
is a way to declare side-effects (networking, storage, ...), and Subscription
is a way to subscribe outer changes (like notifications).
Please read here for the details.
struct AppState {
// MODEL
var value: Int
// UPDATE
enum Message {
case increment
case decrement
case save
case load
case loaded(Int)
}
mutating func update(_ message: Message) -> [Command<Message>] {
switch message {
case .increment:
value = value + 1
return []
case .decrement:
value = value - 1
return []
case .save:
return [.save(value: value)]
case .load:
return [.load(available: { .loaded($0) })]
case .loaded(let value):
self.value = value
return []
}
}
// SUBSCRIPTIONS
var subscriptions: [Subscription<Message>] {
return [
.notification(
name: UIApplication.didBecomeActiveNotification,
{ notification -> Message in
return .load
}),
.notification(
name: UIApplication.willResignActiveNotification,
{ notification -> Message in
return .save
})
]
}
// VIEW
var viewController: ViewController<Message> {
return ._viewController(
.stackView(
views: [
.button(text: "-", onTap: .decrement),
.label(text: "\(value)"),
.button(text: "+", onTap: .increment),
.button(text: "save", onTap: .save),
.button(text: "load", onTap: .load)
],
axis: .vertical,
distribution: .fillEqually
)
)
}
}
- 1st version
- App Architecture from objc.io
- book & video
- sample codes
- especially, Recordings-TEA & One-App-Eight-Architectures