-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConnect.swift
More file actions
66 lines (58 loc) · 1.68 KB
/
Connect.swift
File metadata and controls
66 lines (58 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Created by Gil Birman on 1/11/20.
import SwiftUI
/// Inject a Cloe Store into a SwiftUI view
///
/// Example usage:
///
/// struct MyView: View {
/// var index: Int
///
/// // Define your derived state
/// struct MyDerivedState: Equatable {
/// var age: Int
/// var name: String
/// }
///
/// // Inject your store
/// @EnvironmentObject var store: AppStore
///
/// // Connect to the store
/// var body: some View {
/// Connect(store: store, selector: selector, content: body)
/// }
///
/// // Setup a state selector
/// private func selector(_ state: AppState) -> MyDerivedState {
/// .init(age: state.age, name: state.names[index])
/// }
///
/// // Render something using the selected state
/// private func body(_ state: MyDerivedState) -> some View {
/// Text("Hello \(state.name)!")
/// }
/// }
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public struct Connect<State, SubState: Equatable, Content: View>: View {
// MARK: Public
public var store: Store<State>
public var selector: StateSelector<State, SubState>
public var content: (SubState) -> Content
public init(
store: Store<State>,
selector: @escaping StateSelector<State, SubState>,
content: @escaping (SubState) -> Content)
{
self.store = store
self.selector = selector
self.content = content
}
public var body: some View {
Group {
(state ?? selector(store.state)).map(content)
}.onReceive(store.uniqueSubStatePublisher(selector)) { state in
self.state = state
}
}
// MARK: Private
@SwiftUI.State private var state: SubState?
}