Skip to content

Commit

Permalink
Use Fruitties ViewModel on iOS (#34)
Browse files Browse the repository at this point in the history
* Require iOS 17
* Create IOSViewModelOwner in native source set
* Instantiate IOSViewModelOwner in iOSApp.swift
* Add helper function MainViewModel.newCreationExtras()
* Instantiate MainViewModel in IOSViewModelOwner
* collect() KMP StateFlow to State with SKIE preview API
  * https://skie.touchlab.co/features/flows-in-swiftui
* Delete UIModel and use ViewModel directly
* Cart calculates total items, not number of distinct items
* Simplify Fruitties UI to match Android & iOS
* Android edge-to-edge: Use contentWindowInsets to allow drawing to Bottom edge
* Android: Use CenterAlignedTopAppBar in Scaffold
  • Loading branch information
cartland authored Sep 26, 2024
1 parent 36d62a1 commit 359b809
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 163 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package com.example.fruitties.android
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
Expand All @@ -28,6 +29,7 @@ import com.example.fruitties.android.ui.ListScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MyApplicationTheme {
Surface(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,31 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
Expand All @@ -49,18 +56,17 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.MutableCreationExtras
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.fruitties.android.R
import com.example.fruitties.android.di.App
import com.example.fruitties.database.CartItemDetails
import com.example.fruitties.model.CartItemDetails
import com.example.fruitties.model.Fruittie
import com.example.fruitties.viewmodel.MainViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListScreen() {
// Instantiate a ViewModel with a dependency on the AppContainer.
Expand All @@ -70,45 +76,49 @@ fun ListScreen() {
// so it can be passed to the ViewModel factory.
val app = LocalContext.current.applicationContext as App
val extras = remember(app) {
MutableCreationExtras().apply {
set(MainViewModel.APP_CONTAINER_KEY, app.container)
}
val container = app.container
MainViewModel.newCreationExtras(container)
}
val viewModel: MainViewModel = viewModel(
factory = MainViewModel.Factory,
extras = extras,
)

val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.homeUiState.collectAsState()
val cartState by viewModel.cartUiState.collectAsState()

Scaffold(
topBar = {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.background(MaterialTheme.colorScheme.primary),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(R.string.frutties),
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier
.padding(vertical = 16.dp, horizontal = 16.dp)
.weight(1.0f),
textAlign = TextAlign.Center,
)
}
CenterAlignedTopAppBar(
title = {
Text(text = stringResource(R.string.frutties),)
},
colors = TopAppBarColors(
containerColor = MaterialTheme.colorScheme.primary,
scrolledContainerColor = MaterialTheme.colorScheme.primary,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
titleContentColor = MaterialTheme.colorScheme.onPrimary,
actionIconContentColor = MaterialTheme.colorScheme.onPrimary,
),
)
},
) {
contentWindowInsets = WindowInsets.safeDrawing.only(
// Do not include Bottom so scrolled content is drawn below system bars.
// Include Horizontal because some devices have camera cutouts on the side.
WindowInsetsSides.Top + WindowInsetsSides.Horizontal
),
) { paddingValues ->
Column(
modifier = Modifier.padding(it),
modifier = Modifier
// Support edge-to-edge (required on Android 15)
// https://developer.android.com/develop/ui/compose/layouts/insets#inset-size
.padding(paddingValues),
) {
var expanded by remember { mutableStateOf(false) }
Row(modifier = Modifier.padding(16.dp)) {
val total = cartState.cartDetails.sumOf { item -> item.count }
Text(
text = "Cart has ${cartState.itemList.count()} items",
text = "Cart has $total items",
modifier = Modifier.weight(1f).padding(12.dp),
)
Button(onClick = { expanded = !expanded }) {
Expand All @@ -120,16 +130,25 @@ fun ListScreen() {
enter = fadeIn(animationSpec = tween(1000)),
exit = fadeOut(animationSpec = tween(1000)),
) {
CartDetailsView(cartState.itemList)
CartDetailsView(cartState.cartDetails)
}

LazyColumn {
items(items = uiState.itemList, key = { it.id }) { item ->
items(items = uiState.fruitties, key = { it.id }) { item ->
FruittieItem(
item = item,
onAddToCart = viewModel::addItemToCart,
)
}
// Support edge-to-edge (required on Android 15)
// https://developer.android.com/develop/ui/compose/layouts/insets#inset-size
item {
Spacer(
Modifier.windowInsetsBottomHeight(
WindowInsets.systemBars
)
)
}
}
}
}
Expand Down Expand Up @@ -202,7 +221,7 @@ fun CartDetailsView(cart: List<CartItemDetails>, modifier: Modifier = Modifier)
modifier.padding(horizontal = 32.dp),
) {
cart.forEach { item ->
Text(text = "${item.fruittie.name} : ${item.count}")
Text(text = "${item.fruittie.name}: ${item.count}")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Fruitties/androidApp/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
limitations under the License.
-->
<resources>
<string name="frutties">"Frutties "</string>
<string name="frutties">"Frutties"</string>
<string name="save">Save</string>
<string name="add">Add</string>
<string name="loading">Loading</string>
Expand Down
22 changes: 15 additions & 7 deletions Fruitties/iosApp/iosApp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
};
objectVersion = 50;
objects = {

/* Begin PBXBuildFile section */
058557BB273AAA24004C7B11 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 058557BA273AAA24004C7B11 /* Assets.xcassets */; };
058557D9273AAEEB004C7B11 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 058557D8273AAEEB004C7B11 /* Preview Assets.xcassets */; };
2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2152FB032600AC8F00CF470E /* iOSApp.swift */; };
2E8773602BC85C2400BF7C40 /* CartView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E87735F2BC85C2400BF7C40 /* CartView.swift */; };
2E8773622BCD904A00BF7C40 /* StateHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E8773612BCD904A00BF7C40 /* StateHelper.swift */; };
7555FF83242A565900829871 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7555FF82242A565900829871 /* ContentView.swift */; };
/* End PBXBuildFile section */

/* Begin PBXCopyFilesBuildPhase section */
7555FFB4242A642300829871 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
Expand All @@ -25,16 +26,17 @@
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
058557BA273AAA24004C7B11 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
058557D8273AAEEB004C7B11 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
2152FB032600AC8F00CF470E /* iOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iOSApp.swift; sourceTree = "<group>"; };
2E87735F2BC85C2400BF7C40 /* CartView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CartView.swift; sourceTree = "<group>"; };
2E8773612BCD904A00BF7C40 /* StateHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StateHelper.swift; sourceTree = "<group>"; };
7555FF7B242A565900829871 /* iosApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
7555FF82242A565900829871 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
7555FF8C242A565B00829871 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
7555FF78242A565900829871 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
Expand All @@ -44,6 +46,7 @@
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
058557D7273AAEEB004C7B11 /* Preview Content */ = {
isa = PBXGroup;
Expand Down Expand Up @@ -79,7 +82,6 @@
2152FB032600AC8F00CF470E /* iOSApp.swift */,
058557D7273AAEEB004C7B11 /* Preview Content */,
2E87735F2BC85C2400BF7C40 /* CartView.swift */,
2E8773612BCD904A00BF7C40 /* StateHelper.swift */,
);
path = iosApp;
sourceTree = "<group>";
Expand All @@ -92,6 +94,7 @@
sourceTree = "<group>";
};
/* End PBXGroup section */

/* Begin PBXNativeTarget section */
7555FF7A242A565900829871 /* iosApp */ = {
isa = PBXNativeTarget;
Expand All @@ -113,6 +116,7 @@
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */

/* Begin PBXProject section */
7555FF73242A565900829871 /* Project object */ = {
isa = PBXProject;
Expand Down Expand Up @@ -143,6 +147,7 @@
);
};
/* End PBXProject section */

/* Begin PBXResourcesBuildPhase section */
7555FF79242A565900829871 /* Resources */ = {
isa = PBXResourcesBuildPhase;
Expand All @@ -154,6 +159,7 @@
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */

/* Begin PBXShellScriptBuildPhase section */
7555FFB5242A651A00829871 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
Expand All @@ -173,19 +179,20 @@
shellScript = "cd \"$SRCROOT/..\"\n./gradlew :shared:embedAndSignAppleFrameworkForXcode\n";
};
/* End PBXShellScriptBuildPhase section */

/* Begin PBXSourcesBuildPhase section */
7555FF77242A565900829871 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2E8773602BC85C2400BF7C40 /* CartView.swift in Sources */,
2E8773622BCD904A00BF7C40 /* StateHelper.swift in Sources */,
2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */,
7555FF83242A565900829871 /* ContentView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */

/* Begin XCBuildConfiguration section */
7555FFA3242A565B00829871 /* Debug */ = {
isa = XCBuildConfiguration;
Expand Down Expand Up @@ -315,7 +322,7 @@
"$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
);
INFOPLIST_FILE = iosApp/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
Expand Down Expand Up @@ -344,7 +351,7 @@
"$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
);
INFOPLIST_FILE = iosApp/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
Expand All @@ -362,6 +369,7 @@
name = Release;
};
/* End XCBuildConfiguration section */

/* Begin XCConfigurationList section */
7555FF76242A565900829871 /* Build configuration list for PBXProject "iosApp" */ = {
isa = XCConfigurationList;
Expand All @@ -384,4 +392,4 @@
/* End XCConfigurationList section */
};
rootObject = 7555FF73242A565900829871 /* Project object */;
}
}
35 changes: 24 additions & 11 deletions Fruitties/iosApp/iosApp/CartView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,22 @@ import SwiftUI
import shared

struct CartView : View {
let cart: Cart
let dataRepository: DataRepository
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 {
if (cart.items.isEmpty) {
Text("Cart is empty, add some items").padding()
} else {
VStack {
HStack {
Text("Cart has \(cart.items.count) items").padding()
let total = cartUIState.cartDetails.reduce(0) { $0 + ($1.count) }
Text("Cart has \(total) items").padding()
Spacer()
Button {
expanded.toggle()
Expand All @@ -42,22 +47,30 @@ struct CartView : View {
}.padding()
}
if (expanded) {
CartDetailsView(dataRepository: dataRepository)
CartDetailsView(mainViewModel: mainViewModel)
}
}
// https://skie.touchlab.co/features/flows-in-swiftui
.collect(flow: self.mainViewModel.cartUiState, into: $cartUIState)
}
}

struct CartDetailsView: View {
let dataRepository: DataRepository
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
private var details: CartDetails = CartDetails(items: [])
var cartUIState: CartUiState = CartUiState(cartDetails: [])

var body: some View {
VStack {
ForEach(details.items, id: \.fruittie.id) { item in
ForEach(cartUIState.cartDetails, id: \.fruittie.id) { item in
Text("\(item.fruittie.name): \(item.count)")
}
}.collectWithLifecycle(dataRepository.cartDetails, binding: $details)
}
// https://skie.touchlab.co/features/flows-in-swiftui
.collect(flow: mainViewModel.cartUiState, into: $cartUIState)
}
}
Loading

0 comments on commit 359b809

Please sign in to comment.