https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
c

Clément Cardonnel

07/25/2022, 8:15 AM
Hello, I come from a background of iOS (SwiftUI) programming and I’m very new to Android and Jetpack Compose. I was wondering how Navigation is supposed to work in Compose. Specifically, I’m wondering how you’re supposed to send a lot of data from one screen to another. Let’s say for example that I have a screen with a list of all natural parks in the US. I fetched this list from my backend, and each park is a Park object with many details. When the user selects a park, the app navigates to a park detail screen featuring all the park informations. Now, I’ve looked at the documentation, and it looks like we can send arguments to the next screen. But these arguments look like they were designed for small strings such as an id. Not for sending a whole object. I saw someone on StackOverflow say that you could serialize the Park object into a JSON string and send it as an argument. But this doesn’t feel like a good practice and I’m wary of using it. What is the correct thing to do in this case? Multiple ideas came to mind, but I don’t know which one is best: A. Send a serialized JSON string as a navigation argument B. Send only the park’s id and fetch the park once again in the detail screen. Whether by making a brand new request or fetching it from a cache C. Pass down a view model of some sort to the detail screen. The view model being shared between the list and the detail. D. Something I didn’t think about? Thank you in advance for your help!
m

myanmarking

07/25/2022, 8:18 AM
yeish. You use compose navigation you have to deal with it 😛 My advice, do not use it, or use some other library that does that for you like raamcosta https://github.com/raamcosta/compose-destinations
a

Arkadii Ivanov

07/25/2022, 8:32 AM
If that's really a lot of information for each park, then you have to either store it in a database, or fetch from the backend. The amount of information you can send is limited to ~500 Kb per process, if I remember correctly. None of the libraries will help with big amounts of data. For relatively small data you can try libs, e.g. https://github.com/arkivanov/Decompose
c

Clément Cardonnel

07/25/2022, 8:50 AM
Wow! I didn’t expect the solution was to use a third-party library for this 😄 It looks like Compose Destinations is actually serializing parameters under the hood… I’ll definitely look into it since it solves other issues I had with the standard compose navigation (type-unsafe navigation using strings) The Park objects aren’t supposed to be that big. They will mainly be plain text, with any asset simply being represented with URLs. I’d be surprised if a park could reach the limit, but you never know. However, using a database would be a lot of work. Even more so since I already have a comprehensive caching mechanism. I’m using GraphQL, with SQLite local storage and cache normalization. So making a new network request is actually feasible without much of a penaly. Maybe I should go with option B then?
a

Arkadii Ivanov

07/25/2022, 8:59 AM
You have to use a library for navigation anyway. There is a first-party library - AndroidX navigation-compose, and many third-party, e.g. those mentioned above. Libraries that allow passing objects between destinations have to always serialize the data at some point. Because of the Android configuration changes or possible process death, so the navigation stack is preserved and all the data is restored. If you think your objects are not big, then you can try a third-party library.
c

Clément Cardonnel

07/25/2022, 9:00 AM
Alright, thank you very much for the advice 😊
m

Michael Paus

07/25/2022, 9:02 AM
If you have a pure Compose app you can just switch off all these configuration changes in the manifest. After that life is much easier.
c

Clément Cardonnel

07/25/2022, 9:05 AM
@Michael Paus I’m actually pursuing the road of the pure compose app. My app just has a single activity and everything inside is just Compose for now. I’m sorry that I’m not experienced enough to know what these configuration changes are, but what would be the actual benefit from switching them off?
m

Michael Paus

07/25/2022, 9:09 AM
The benefits are, e.g, that your activity is not restarted anymore when you just rotate your device. Compose handles that for you and you do not constantly have to serialise/deserialise things.
:thank-you: 1
I just keep my model in memory and that works nicely so far.
a

Arkadii Ivanov

07/25/2022, 9:11 AM
How does it solve the issue with passing classes between screens?
m

Michael Paus

07/25/2022, 9:12 AM
Here is a fragment of my manifest:
android:configChanges="colorMode|density|fontScale|keyboard|keyboardHidden|layoutDirection|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode">
@Arkadii Ivanov I use a centralised model in my app and I never had the need to pass any data between screens.
a

Arkadii Ivanov

07/25/2022, 9:15 AM
Ah alright thanks! That's indeed a solution with its pros and cons.
m

Michael Paus

07/25/2022, 9:19 AM
Could you give a few examples of the “cons”? I have to admit that I primarily have a desktop background and I often do not understand why Android programmers often do things in so complicated ways. I never felt the need for such things on desktop. One reason are these config changes but when you can get rid of them I don’t see any other reasons.
a

Arkadii Ivanov

07/25/2022, 9:26 AM
@Michael Paus the biggest one is the possible process death while the app is in the background. The aggressiveness may vary between device models/brands. And on some low-cost devices it's quite likely that your app will be killed when you are taking a picture or recording a video using e.g. the system camera app. Or the user may switch to a memory consuming app (a game) for a moment and then go back to your app, and boom - your stack is reset and the user lands to the initial screen. Another possible downside is that you have to maintain the back stack on your own. E.g. you normally will have to preserve the UI state when switching screens. A use case - you scroll a list, pick an item, a details screen shows, you close the details screen - the scrolling position usually should remain unchanged. Also, a centralized model may lead to a coupling between screens, which may be less scalable in medium/large projects.
m

Michael Paus

07/25/2022, 9:39 AM
These are some interesting points to look at although I have not yet suffered from them and I think that most of them could be solved in a more light-weight fashion. But I do not want to conquer this thread 😉.
❤️ 1
i

Ian Lake

07/25/2022, 1:55 PM
Note that on Android 12+, you cannot ever catch all config changes - a wallpaper change will force your activity to go through a config change (to update the dynamic colors, even if your app doesn't actually read them), no matter what flags you have set (it ends up going through a completely different system). This effectively means you must always handle config changes
☝️ 1
The correct is, as per many previous threads, is that both screens should be talking to a single, observable source of truth (e.g., a repository layer): https://kotlinlang.slack.com/archives/CJLTWPH7S/p1657897289085069?thread_ts=1657844159.552379&cid=CJLTWPH7S
c

Colton Idle

07/25/2022, 2:10 PM
@Clément Cardonnel the best way I like to think about these things are as scopes. So if you have an app that is single activity and two Composable screens (ScreenA and ScreenB), then you can have a ScreenAViewModel and ScreenBViewModel. which are scoped as expected to just their screen, and then you find yourself in the perdicament you are in now. BUT there are still two more scopes available to you to store that data. 1. The navHost scope/activity scope. These are effectively the same thing, but you can just create a ViewModel for your navHost or for your Activity, and then put any shared data in there. 2. The application scope which is overarching to your entire application. This is where I like to put data I need on every screen. Like my User model, but on certain apps where a lot of the screens use the same list of data then I might also put it there.
i

Ian Lake

07/25/2022, 2:11 PM
Very rarely does your Park object exist solely at the UI layer, which would be the only case where using a static argument as your source of truth would make sense
c

Colton Idle

07/25/2022, 2:11 PM
@Ian Lake with a repository layer solution, that repository is effectively application scoped, correct?
i

Ian Lake

07/25/2022, 2:12 PM
That depends entirely on your DI setup, but that is indeed the most obvious way to set things up
👍 1
m

Michael Paus

07/25/2022, 6:17 PM
An application scoped repository layer was what I basically meant when I said that I use a centralised model.
a

Arkadii Ivanov

07/25/2022, 6:57 PM
@Michael Paus please note, that the repository should be persistent in this case. And I believe it still implies that the navigation stack and arguments are persistent as well. With this approach you just pass an item id, and another screen loads all the data from the repository.
m

Michael Paus

07/25/2022, 7:59 PM
Of course. At some point you have to persist whatever needs to be persisted in case the app is terminated. I distinguish though between the UI state and the model state. In my specific case I do not care much when I should loose the UI state (a use-case specific decision) and I just start from the beginning by reading the persisted model state. But I just don’t see why I should go through the whole persistence cycle with some weird serialisation as mentioned above just because I am going from one screen to the other, which is a much more frequent action. Note, in Compose terms a screen is not the same as an activity. I assume a single activity Compose app here. When going from one screen to the other the needed data is just taken from the model which hopefully has that cached and does not have to load it again.
i

Ian Lake

07/25/2022, 9:17 PM
that makes some big assumptions - your app can and will go through config changes or process death and recreation when on any screen of your app (think: the user quickly opens the camera to take a picture of their kid, then comes back to your app - tada - process death and recreation). Each screen needs to be able to restore itself from saved instance state (the small bits of data ala the IDs you are supposed to be passing) and persisted / re-queried from scratch data
c

Colton Idle

07/25/2022, 10:00 PM
I'm happy Android studio added the button back to quickly test process death. 😁
m

Michael Paus

07/25/2022, 10:28 PM
I don’t argue against saving the UI state if you need to. There are means to do that and it is in general just a small amount of data but I do not see any reason to push large amounts of data around for every single screen change as the original author of this thread suggested. Especially not on limited devices.