Skip to content

Commit

Permalink
Switch to Observing API in swift (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
bentrengrove authored Oct 2, 2024
1 parent ac12d4e commit b1e0e10
Showing 1 changed file with 26 additions and 36 deletions.
62 changes: 26 additions & 36 deletions Fruitties/iosApp/iosApp/CartView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,56 +21,46 @@ import shared
struct CartView : View {
let mainViewModel: MainViewModel

// The ViewModel exposes a StateFlow.
// We collect() the StateFlow into State, which can be used in SwiftUI.
// https://skie.touchlab.co/features/flows-in-swiftui
@State
var cartUIState: CartUiState = CartUiState(cartDetails: [])

@State
private var expanded = false

var body: some View {
VStack {
HStack {
let total = cartUIState.cartDetails.reduce(0) { $0 + ($1.count) }
Text("Cart has \(total) items").padding()
Spacer()
Button {
expanded.toggle()
} label: {
if (expanded) {
Text("collapse")
} else {
Text("expand")
}
}.padding()
}
if (expanded) {
CartDetailsView(mainViewModel: mainViewModel)
// https://skie.touchlab.co/features/flows-in-swiftui
Observing(self.mainViewModel.cartUiState) { cartUIState in

This comment has been minimized.

Copy link
@cartland

cartland Oct 7, 2024

Contributor

@bentrengrove you could also make this change in ContentView.swift

VStack {
HStack {
let total = cartUIState.cartDetails.reduce(0) { $0 + $1.count }
Text("Cart has \(total) items").padding()
Spacer()
Button {
expanded.toggle()
} label: {
if (expanded) {
Text("collapse")
} else {
Text("expand")
}
}.padding()
}
if (expanded) {
CartDetailsView(mainViewModel: mainViewModel)
}
}
}
// https://skie.touchlab.co/features/flows-in-swiftui
.collect(flow: self.mainViewModel.cartUiState, into: $cartUIState)
}
}

struct CartDetailsView: View {
let mainViewModel: MainViewModel

// The ViewModel exposes a StateFlow.
// We collect() the StateFlow into State, which can be used in SwiftUI.
// https://skie.touchlab.co/features/flows-in-swiftui
@State
var cartUIState: CartUiState = CartUiState(cartDetails: [])

var body: some View {
VStack {
ForEach(cartUIState.cartDetails, id: \.fruittie.id) { item in
Text("\(item.fruittie.name): \(item.count)")

Observing(self.mainViewModel.cartUiState) { cartUIState in
VStack {
ForEach(cartUIState.cartDetails, id: \.fruittie.id) { item in
Text("\(item.fruittie.name): \(item.count)")
}
}
}
// https://skie.touchlab.co/features/flows-in-swiftui
.collect(flow: mainViewModel.cartUiState, into: $cartUIState)
}
}

0 comments on commit b1e0e10

Please sign in to comment.