https://kotlinlang.org logo
Join the conversationJoin Slack
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
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
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
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 Linen
compose
  • w

    why

    09/02/2021, 12:39 PM
    Hi, so in a new Compose app project with only one
    OutlinedTextField
    , the memory profiler, after setting focus on/selecting the text field without typing anything, shows that Java allocations are happening non-stop, it keeps goin up until it gets GCed, then start going up again over n over, am I missing something?
    MyApplicationTheme {
        // A surface container using the 'background' color from the theme
        Surface(color = MaterialTheme.colors.background) {
            OutlinedTextField(value = "Ok", onValueChange = {})
        }
    }
    j
    • 2
    • 2
  • b

    Bacho Kurtanidze

    09/02/2021, 12:55 PM
    constrainAs(title_textRef, { end.linkTo(parent.end, ~dimensionResource~(id = R.dimen.dp_16)) } How can I reference dimensionResource inside of non-composable code block?
    c
    • 2
    • 1
  • s

    Scott Kruse

    09/02/2021, 2:28 PM
    Random thought, it would be useful to have a XML -> Compose conversion tool in the IDE
    a
    a
    a
    • 4
    • 4
  • t

    Tolriq

    09/02/2021, 4:43 PM
    What would be the proper way to animate a bottomnavigationbar in a scaffold when expanding a bottomsheet? Applying an offset is not enough as it leaves the padding to the content and also changing the height via a modifier triggers too many recomposition and seems to break the swiping 😞
    f
    c
    • 3
    • 11
  • c

    Chris Johnson

    09/02/2021, 7:03 PM
    :android-wave: Is there a way to measure a child before placing it and then fill the screen with the available amount of those children? Currently I'm creating a
    Layout
    for measurement of the child and then another
    Layout
    that will place X amount of those children based on screen height. The problem I ran into was each child I'm placing needs to be unique/not being currently laid out for the system to not give me
    "Place was called on a node which was placed already"
    .
    z
    • 2
    • 10
  • a

    Anthony

    09/02/2021, 7:38 PM
    Has anyone tried out
    androidx.navigation:navigation-compose:2.4.0-alpha08
    yet? I seem to be getting an error every time I navigate back to a composable using a navigation graph scope viewmodel.
    👍 1
    i
    • 2
    • 10
  • l

    Lilly

    09/02/2021, 9:49 PM
    What is the right way to handle
    Flow
    that comes from view model? I have a
    Flow
    that produces values for
    LazyColumn
    . Do I have to put the values into a
    SnapshotStateList
    or can I feed the
    LazyColumn
    on the fly with the values? How would I do this?
    z
    l
    • 3
    • 17
  • s

    Sanendak

    09/02/2021, 10:21 PM
    Hello guys! I have a question about conditional navigation. User can see start destination screen (Dashboard) and transition to sign in screen when isn't logged. Chain: 1. Check boolean from datastore flow in start destination screen (Dashboard) 2. In the Dashboard screen: if(isLogged) { Dashboard composable } else navigate to sign in How to fix this issue?
    f
    f
    • 3
    • 15
  • n

    Napa Ram

    09/03/2021, 5:48 AM
    is there a way to handle life cycle as we are not using fragment and only one activity is there is project, i need inform view model 1. when compose screen created 2. when app go in background 3. when moving from one screen to another and when we are coming back to same screen 4. basically all lifecycle event
    j
    a
    +2
    • 5
    • 7
  • a

    allan.conda

    09/03/2021, 5:50 AM
    We’re trying to render relative time accurately in Compose:
    val displayTime = remember(message.createdTime) {
        DateUtils.getRelativeTimeSpanString(message.createdTime * 1_000).toString()
    }
    Text(displayTime)
    When we refresh, we want to update the relative time text but it doesn’t a recomposition when the time value doesn’t change. Any idea how to handle this kind of scenario?
    f
    • 2
    • 2
  • s

    smit01

    09/03/2021, 7:17 AM
    Where can I find kotlin doc like documents for compose. There are some tutorials on YouTube but full fledged documents will help better learning it.
    f
    • 2
    • 1
  • l

    Lilly

    09/03/2021, 12:19 PM
    [SOLVED] I want to grant a permission by using
    val requestPermissionLauncher = rememberLauncherForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            ...
        }
    and
    requestPermissionLauncher.launch(permission)
    . I have discovered that
    requestPermissionLauncher.launch(permission)
    is responsible for opening the "android permission prompt" but triggers the above callback in the first run with
    false
    without waiting for a user action. When I click "Allow" btn the callback is triggered with
    true
    . Is the first run with false inteded? Do we have to suspend here and wait for a user action somehow? I would expect that the callback is only triggered when a button of the prompt is clciked.
    f
    i
    • 3
    • 6
  • u

    ursus

    09/03/2021, 12:45 PM
    Has anyone seen an example of how should viewmodel+compose work with dagger? probably to provide the Screen composable woth viewmodel injected somehow?
    c
    • 2
    • 3
  • j

    Joey

    09/03/2021, 12:46 PM
    Is it possible with ScrollableTabRow to add spacing between tabs including the indicator?
    • 1
    • 2
  • t

    tylerwilson

    09/03/2021, 6:55 PM
    I have a layout like so:
    Box(fillMaxWidth) {
       Row(horizontalScroll) {
          items.forEach {
              Column(width(<boxWidth here>) {
              }
           }
       }
    }
    I want to dynamically change the inner column width to be the same as the ancestor box (it should be width of device), or some percentage (half or quarter). How can I reference the Box width in order to size the Column(s) properly? Thank you!
    z
    w
    a
    • 4
    • 25
  • c

    Carl Benson

    09/03/2021, 7:17 PM
    has anyone successfully resized a composable dialog destination using the insets-ui? how do I access the containing
    Dialog
    to
    setDecorFitsSystemWindows
    to false?
    ➕ 2
    t
    • 2
    • 4
  • j

    josefdolezal

    09/03/2021, 9:05 PM
    Hey folks 🖖 , is there a way to animate
    Buttons
    colors based on
    enabled
    ? What comes to my mind is to create my own class implementing
    ButtonColors
    which would then animate the color using
    animateColorAsState
    , but it seems a bit too verbose
    r
    • 2
    • 2
  • a

    adjpd

    09/03/2021, 9:08 PM
    In future, will the Android team continue to create new Android views and then the Jetpack Compose team mimics them, a la
    TextInputLayout
    and
    TextField
    ? Moreover, is there a plan to make Jetpack Compose the primary view system for Android, or just an alternative?
    m
    • 2
    • 3
  • j

    Justin Yue

    09/04/2021, 4:38 AM
    I have a similar issue found in this thread where I am inserting a
    LazyVerticalGrid
    inside a
    Column
    with a scroll state, so I now know that I can't nest composables scrolling in the same direction. However, I'm only using
    LazyVerticalGrid
    since the cells can be adaptive, and I don't need its scroll functionality. Is there a way to create a composable that can replicate `LazyVerticalGrid`'s adaptive functionality and removing the scrolling?
    a
    z
    • 3
    • 3
  • r

    rajesh

    09/04/2021, 10:49 AM
    How do I set min and max size (instead of using
    fillMaxSize()
    ) of box having pinch to zoom ability? code is in thread.
    a
    • 2
    • 3
  • l

    Lorenzo Benevento

    09/04/2021, 11:56 AM
    How would you implement multiple `ModalBottomSheet`s? I found this article which explains how to do it using a
    BottomSheetScaffold
    but as soon as you try to do the same thing with a
    ModalBottomSheetLayout
    it throws
    java.lang.IllegalArgumentException: The initial value must have an associated anchor.
    because you are initializing it with a null value. If you just swap the two or more contents instead of setting a null value when you close the
    ModalBottomSheet
    it will work but it won't animate correctly.
    j
    • 2
    • 3
  • s

    Se7eN

    09/04/2021, 1:53 PM
    Probably not compose related, but how can I create an immutable copy of an object from a mutable one?
    class Element {
        var position: Offset by mutableStateOf(...)
        var rotation: Float by mutableStateOf(...)
        ...
    }
    
    // Then I can do this:
    val element = Element(...)
    element.position = newPosition
    I want to pass this
    element
    object to a composable but don't want it to be mutable. I can create a similar class for an immutable element but then I'd have to update the immutable class whenever I change the
    Element
    class. Is there something else I can do?
    z
    • 2
    • 4
  • f

    Fudge

    09/04/2021, 2:39 PM
    Is there a way to get the absolute layout position in
    Layout
    ? the use case is to animate a component moving from one part of the screen to another.
    h
    a
    • 3
    • 6
  • r

    rajesh

    09/04/2021, 5:55 PM
    Is there any way to decorate
    TextField
    ?
    BasicTextField
    support decoration but lacks some of the features that
    TextField
    provides like leading icon. Is there any custom text field created by someone ?
    a
    • 2
    • 1
  • a

    adjpd

    09/04/2021, 7:01 PM
    The docs state that if you use the below as
    rememberCoroutineScope().launch { }
    then bugs may appear; since Compose can call the composables at any moment. In this scenario, or in any scenario, when is it likely to happen? I understand the concept but I can't think of any examples when this may actually happen.
    LaunchedEffect(onTimeout) {
      delay(SplashWaitTime)
      onTimeout()
    }
    z
    • 2
    • 1
  • c

    Colton Idle

    09/05/2021, 2:34 AM
    I have a column with horizontal padding
    Column(modifier = Modifier.padding(horizontal = 16.dp)) {
    every item need the horizontal padding except for 1 item in the col. Is there an easy way to "opt out"?
    c
    w
    • 3
    • 2
  • c

    Colton Idle

    09/05/2021, 4:01 AM
    Not sure if I'm using flow + collectAsState correctly (it's my first time using a Flow, but a library I'm using exposes a flow, so I suppose it makes sense to use it) Code in thread
    k
    r
    +6
    • 9
    • 25
  • s

    shahroz

    09/05/2021, 8:54 AM
    Whats the best approach to handle actions when it comes to Bottom Sheet? I am using Accompanist Navigation Material , if i navigate from one Composable to BottomSheet one, and in the bottom sheet I have couple of actions that i can perform, but i need to transmit the action callbacks upstream as well, what would be the best way to do this? cc @jossiwolf
    c
    i
    • 3
    • 5
  • b

    bitkiller

    09/05/2021, 3:04 PM
    Trying to build a simple color picker in an AlertDialog. On some simple testings, the content (
    text
    ) of the dialog is just
    Column
      Box // clipped to Circle
      Text
    But with this ^ the content is being place over the dialog's title.
    a
    z
    • 3
    • 7
  • v

    Viktor Petrovski

    09/05/2021, 8:21 PM
    Hello, I’m having a weird issue which I can’t really understand the problem. To simplify things, I have two Composables, SplashScreen & HomeScreen. I need to make a network request on the SplashScreen and then navigate to HomeScreen when the endpoint succeeds. Code in thread 👇
    ➕ 1
    c
    i
    a
    • 4
    • 15
Powered by Linen
Title
v

Viktor Petrovski

09/05/2021, 8:21 PM
Hello, I’m having a weird issue which I can’t really understand the problem. To simplify things, I have two Composables, SplashScreen & HomeScreen. I need to make a network request on the SplashScreen and then navigate to HomeScreen when the endpoint succeeds. Code in thread 👇
➕ 1
c

Colton Idle

09/05/2021, 8:22 PM
@Viktor Petrovski can you edit your post to put the code in this thread please? https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616265877303000
v

Viktor Petrovski

09/05/2021, 8:23 PM
Yes sure, sorry @Colton Idle
NavigationCode:
@Composable
fun Navigation() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = Screens.SplashScreen.route) {
        composable(Screens.SplashScreen.route) {
            val authViewModel = hiltViewModel<AuthViewModel>(it)
            SplashScreen(authViewModel, navController)
        }
        composable(Screens.Home.route) {
            val feedViewModel = hiltViewModel<FeedViewModel>()
            HomeFeedScreen(feedViewModel.state.value)
        }
    }
}

@Composable
fun SplashScreen(
    viewModel: AuthViewModel,
    navController: NavController
) {
    val state = viewModel.state.collectAsState()
    if (state.value.isSuccess) {
        navController.navigate(Screens.Home.route) {
            popUpTo(Screens.SplashScreen.route) {
                inclusive = true
            }
        }
    } else {
        // Render view...
    }
ViewModel:
@HiltViewModel
class AuthViewModel
@Inject constructor(private val useCase: CreateAnonymousUserUseCase) :
    ViewModel() {
    private val _state: MutableStateFlow<AnonAuthResponse> = MutableStateFlow(AnonAuthResponse())
    val state: StateFlow<AnonAuthResponse> = _state

    init {
        crateAnonUser()
    }

    private fun crateAnonUser() {
        viewModelScope.launch {
            useCase.createAnonymousUser().collect {
                _state.value = _state.value.copy(isSuccess = it.isSuccess, loading = it.loading)
            }
        }
    }
}
Added delay instead of the actual network request to maket things easier:
fun createAnonymousUser(): Flow<AnonAuthResponse> = flow {
    kotlinx.coroutines.delay(2500)
    emit(AnonAuthResponse(isSuccess = true))
}
If I remove the delay everything works fine, but when I add it it keeps on navigating to HomeScreen and re-rendering the SplashScreen. Thanks 🙏
➕ 1
i

Ian Lake

09/05/2021, 9:53 PM
You're calling
navigate()
as part of composition. That's always wrong (composition should never have side effects) - you'll end up calling
navigate()
on every frame of the animation between destinations, which is absolutely not what you want
But taking a step back, you should never have a splash screen destination as your start destination of your app as per the https://developer.android.com/guide/navigation/navigation-principles#fixed_start_destination
We've talked about login and these cases (and why they never work as the start destination of your app, particularly when you take into account process death and recreation and deep links) multiple times here in the past, such as: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1626727460044100?thread_ts=1626726997.043700&amp;cid=CJLTWPH7S
➕ 2
c

Colton Idle

09/05/2021, 9:59 PM
Sorry to piggyback onto this, but Ian do you know if there's any sample that shows this sort of login scenario in compose. I basically have this working in my app because of all of your help, but I'm still"worried" that the way that I observe my loggedIn state and therefore triggering a move to the SignInScreen composable isn't right. Just trying to see if this is something that is already in some sample I can copy.
a

adjpd

09/05/2021, 10:42 PM
In the pathway tutorial, the final advanced segment, there's a section that deals with a splash screen.
c

Colton Idle

09/05/2021, 10:58 PM
Ooh. Thanks. Will take a look.
v

Viktor Petrovski

09/06/2021, 7:35 AM
Thanks @Ian Lake on your detailed response, will take a look at resources about setting up the start destination correctly. Soo back to my original question, when we want to navigate somewhere when a state changes ( in this case upon successfull log in) if we don’t want to call navigate from compose should we move the navigation logic in our ViewModel? I guess something like what Joe Brich is talking in his blog post https://medium.com/google-developer-experts/modular-navigation-with-jetpack-compose-fda9f6b2bef7?
i

Ian Lake

09/06/2021, 2:41 PM
No, you don't have to do all that - processing events is something you do in one of the effect methods, such as `LaunchedEffect`:
if (state.value.isSuccess) {
  // Use the value as the key
  // so that it only happens once
  LaunchedEffect(state.value) {
    // Call navigate here
  }
}
👍 1
v

Viktor Petrovski

09/06/2021, 2:42 PM
Oh Interesting, thanks! 🙌🙌
c

Colton Idle

09/06/2021, 5:24 PM
@Ian Lake why wouldn't it be
LaunchedEffect(state.value.isSuccess)
?
v

Viktor Petrovski

09/06/2021, 5:24 PM
I think it can, I believe it worked both ways for me
👍 1
i

Ian Lake

09/06/2021, 9:22 PM
Ideally you're using
by
and you wouldn't need the
.value
everywhere in the first place, but yes, I was assuming immutable objects where it wouldn't make a difference - the point is that the Launched effect would run just once for a given value change
🎉 2
☝️ 1
👍 1
View count: 3