https://kotlinlang.org logo
Docs
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
  • d

    Daniel

    06/09/2021, 7:18 PM
    How are people handling permission flows with compose? Right now I'm creating methods on my activity like
    ensureFineLocation
    that handles the whole permission flow and then passing a reference to the function down through the composables. This seems like it will scale pretty badly though, both in that the activity has a lot of unrelated methods and I've got to pass a lot of free functions. Also, since
    registerForActivityResult
    is global state I'm not sure the right way to handle repeated calls. I'm currently using a MutableState like so
    private val fineLocationStatus = MutableState<Boolean?>(null)
        private val requestFineLocationLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                fineLocationStatus.value = isGranted
            }
    
       private fun ensureFineLocation(): Boolean {
           val initialCached = fineLocationStatus.value
           if (initialCached != null) {
               if (!initialCached) showFineLocationMissingError()
               return initialCached
           }
    
           val permission = Manifest.permission.ACCESS_FINE_LOCATION
    
            if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) return true
    
            if (shouldShowRequestPermissionRationale(permission)) {
                if (!fineLocationRationalePrompt()) {
                    fineLocationDeniedMsg()
                    return false
                }
            }
    
            requestFineLocationLauncher.launch(permission)
    
            val cached = fineLocationStatus.filterNotNull().first()
            if (!cached) fineLocationDeniedMsg()
            return cached
       }
    This is a little racy if there are multiple calls before a value is cached. I'm also not sure the value should be cached, so I considered clearing the mutable state before returning. Then I think I'd need to protect
    ensureFineLocation
    with a mutex, though. I feel like there has to be a better solution. Is there a reason why
    registerForActivityResult
    uses a global callback instead of giving each request a different requestCode so that you can have a suspend fun like
    launcher.awaitResult
    ?
    i
    m
    • 3
    • 14
  • r

    rook

    06/09/2021, 7:51 PM
    How can I provide
    @Composable
    functions from a compiled aar? Specifically, ensuring that the consuming application has all the necessary compose dependencies and configurations to handle its presence. I want to compose the UI with Compose and then expose it via my API either as a Composable method or as a traditional view component. I’m having trouble finding documentation on this.
    z
    • 2
    • 2
  • d

    Daniel Rampelt

    06/09/2021, 8:35 PM
    I'm having some trouble integrating Compose
    1.0.0-beta08
    into an existing application with Kotlin
    1.5.10
    and AGP
    7.1.0-alpha02
    . I'm getting the following error and I'm not sure how to further debug it. More details in :thread-please:
    java.lang.NoSuchMethodError: No static method setContent$default(...)
    a
    c
    j
    • 4
    • 21
  • e

    eschrag

    06/09/2021, 8:38 PM
    Anyone out there with knowledge of how to use Calabash/Cucumber testing in combination with Compose?
    c
    • 2
    • 6
  • c

    Christopher Elías

    06/10/2021, 4:06 AM
    Hey guys, I'm using compose
    1.0.0-beta08
    but Im not able to use modifiers... every extension is just red on the IDE does someone is having the same issue?
    a
    • 2
    • 5
  • p

    Philip S

    06/10/2021, 5:55 AM
    Having some issues with Espresso and Compose interoperability will post code examples in thread. Espresso seems unable to find Compose elements even if I'm trying to find them by text rather than ID:s. There is the ComposeTestRule class but I can't use that because it does not seems to support launching activities with custom intents? I'm setting the Compose layouts inside fragments
    • 1
    • 2
  • z

    Zach Klippenstein (he/him) [MOD]

    06/10/2021, 6:10 AM
    What’s the expected behavior for components that merge their semantics but have children with content descriptions? It seems like the content description just gets dropped in the merged tree. So e.g. if you have an image inside a clickable, the image’s content description is hidden when reading the merged semantics tree. This seems to work fine for accessibility – talkback will read the content description – but for UI tests, you have to pass
    useUnmergedTree=true
    to the node matcher, which seems unintuitive.
    🐛 1
    • 1
    • 2
  • f

    frankelot

    06/10/2021, 8:30 AM
    👋 Hey, I’m seeing some overlap between
    MutableState<T>
    and
    MutableStateFlow<T>
    , when should I use each?
    r
    g
    +3
    • 6
    • 64
  • l

    louiscad

    06/10/2021, 9:39 AM
    Hello, is there a way to have SystemUI (aka. navbar and statusbar) displayed in the Android Studio preview?
    ✅ 1
    c
    m
    m
    • 4
    • 13
  • a

    Alex Bieliaiev

    06/10/2021, 9:58 AM
    Hi guys, I have a question about
    nestedScroll
    thing. So I have a
    ModalBottomSheetLayout
    and a vertically scrollable column within that bottom sheet.
    ModalBottomSheetLayout
    participates in the nested scrolling (please see
    PreUpPostDownNestedScrollConnection
    ). As far, as I understand the logic,
    ModalBottomSheetLayout
    consumes entire scroll delta through the
    onPreScroll
    , so the actual scroll target (the child column) doesn't receive any delta at all. This results into the bottom sheet being dragged vertically instead of the column being scrolled. Any suggestions?
    a
    • 2
    • 9
  • a

    Akram Bensalem

    06/10/2021, 10:31 AM
    How to detect when the user rise one finger and left the other one in Jetpack compose ?
    f
    • 2
    • 2
  • m

    marios proto

    06/10/2021, 12:02 PM
    👋 I am refactoring part of our app to use Compose, and trying to reuse our MVI viewmodels which a property of
    StateFlow
    of different states. e.g.
    sealed class MyState{
       object Loading…
       class ShowList(val list:List<String> ) …
       class Itemselected( val item:String)...
       class Error( val message:String )…
    }
    and then on the content I want to display something like
    @Composable
        fun MyPage(viewModel: MyViewModel) {
            val state: MyState by viewModel.getStateFlow()
                .collectAsState(initial = MyState.Loading)
            Column {
                Header("Home")
                PageBody(state) 
            }
        }
    @Composable
    fun PageBody(state: ServiceHubHomeState) {
        when (state) {
            MyState.Loading -> Header("Loading")
            is MyState.ShowList ->
                ListHub(serviceItems = state.list) 
            is MyState.ItemSelected -> { // do something else
            }
        }
    }
    So now, when I use .collectAsState, everything works all-right, BUT, when I have already published a value of Showlist, and a list is rendered, if a new state comes, e.g ItemSelected of course the list is cleaned up. My question is, how do I keep the already rendered list between the next state transitions? I am sure I have to keep the state somewhere but cannot see it 😞
    a
    a
    • 3
    • 5
  • p

    Peter Mandeljc

    06/10/2021, 12:15 PM
    anyone had problems with clicking on content, when using
    BottomDrawer
    ?
    @Composable
    fun Screen() = Scaffold {
        BottomDrawer(
            drawerContent = { DrawerContent() },
            content = { ScreenContent() },
        )
    }
    • 1
    • 2
  • d

    dimsuz

    06/10/2021, 12:37 PM
    I have Swipeable switching between 3 states. Inside it there's a LazyColumn. What is the best way to initiate scroll to item 3 in that column once swipeable settles on a certain state? I imagine running LaunchedEffect, but at what point? Should I somehow store previousSwipeableState and check it against a new state and if they differ — fire away? But how to store previous state?
    m
    • 2
    • 2
  • r

    Rodri Represa

    06/10/2021, 2:25 PM
    Does anyone know why after this code my list still filled {0,1,2}
    var test = mutableStateOf<List<Int>>(emptyList())
    /**
     I add some values to test {0,1,2}
    **/
    test = emptyList()
    f
    • 2
    • 8
  • s

    Slackbot

    06/10/2021, 2:48 PM
    This message was deleted.
    z
    • 2
    • 2
  • s

    Superblazer

    06/10/2021, 2:53 PM
    What is the cause for this crash? This happens when I click on a LazyColumn item to navigate to a Composable screen destination, it happens randomly..
    d
    a
    • 3
    • 6
  • j

    Joey

    06/10/2021, 3:03 PM
    I have a composable which consists of 2 parts: The upper part which should have it's height between wrapContent and 33% of the parent height, and a second part that should fill the remaining space, but also take space from the upper part if this second part is larger than the 67% of height left. If there's still more space needed it should turn into a vertical scroller. This is my current code but it's not working, how can I achieve something like my idea?
    • 1
    • 1
  • d

    dimsuz

    06/10/2021, 3:31 PM
    I have an
    Image
    which has
    fillMaxSize()
    and
    contentScale = FillBounds
    , but the painter is still drawn in center of the image, why is that? It seems that contentScale is completely ignored (example in the thread)
    n
    • 2
    • 5
  • t

    tylerwilson

    06/10/2021, 4:44 PM
    Basic question: I want a column half width against the right side of the view/parent. The fillMaxWidth(0.5f) is perfect for the width, but there is no offsetMaxWidth and the offset(x = ) expects dp. What is the simplest way to calc the offset or have it start in the middle? Thanks!
    a
    c
    p
    • 4
    • 5
  • d

    dimsuz

    06/10/2021, 5:14 PM
    LazyListState
    has
    animateBy
    which accepts an
    AnimationSpec
    and it also has
    animateScrollToItem
    which doesn't accept
    AnimationSpec
    and hardcodes it to
    spring()
    . Is this asymmetry on purpose? Or can I request this feature?
    a
    • 2
    • 2
  • r

    Ryan Simon

    06/10/2021, 6:43 PM
    Hey all, I just ran into a weird issue with
    LazyColumn
    and I'm wondering if it's intended behavior. I am observing a
    LiveData
    as
    State
    and whenever it gets updated, the UI should update as expected. The weird thing though is that my
    LazyColumn
    won't update properly unless I use the
    key
    property in the
    items
    extension within the
    LazyListScope
    . Sample code in the thread
    a
    p
    • 3
    • 8
  • z

    Zach Klippenstein (he/him) [MOD]

    06/10/2021, 7:50 PM
    Bumping this since I think it got lost in the scrollback last night. Is it intentional that
    contentDescription
    doesn’t get merged up? More details in the thread on the original message.
    a
    a
    • 3
    • 15
  • d

    Daniel

    06/10/2021, 8:32 PM
    I'm struggling to handle the permission request flow. I think I need to pass down a callback or make my activity a CompositionLocal to access
    shouldShowRequestPermissionRationale()
    . What are people doing?
    a
    c
    m
    • 4
    • 5
  • r

    Ravi

    06/10/2021, 8:38 PM
    anyone have solution to this https://stackoverflow.com/questions/63157554/duplicate-class-found-in-modules. I'm stuck with same problem, old modules using paging-2 and I'm migrating screens to compose which implements
    androidx.paging:paging-compose:1.0.0-alpha10
    m
    • 2
    • 2
  • c

    Christopher Elías

    06/10/2021, 8:49 PM
    Hello guys, I'm using jetpack compose on a project and it's awesome. I'm displaying a Linechart correctly but I believe the performance of the drawing can be improved with coroutines... I'm doing something like this 👇 but it crash with an
    UnsupportedException
    , does anybody has trying to do the same and actually succeed?
    @Composable
    fun LinearTransactionsChart(
        modifier: Modifier = Modifier,
        transactionsPerSecond: TransactionsPerSecond,
        defaultDispatcher: CoroutineDispatcher
    ) {
        if (transactionsPerSecond.transactions.isEmpty()) return
    
        val composableScope = rememberCoroutineScope()
    
        Canvas(modifier = modifier) {
            composableScope.launch(Dispatchers.Main) {
                emitTransactions(
                    defaultDispatcher = defaultDispatcher,
                    maxTransaction = transactionsPerSecond.maxTransaction,
                    transactions = transactionsPerSecond.transactions,
                    canvasWidth = size.width,
                    canvasHeight = size.height
                ) { start, end ->
                    drawLine(
                        start = start,
                        end = end,
                        color = Color(0xFFFFFFFF)
                    )
                }
            }
        }
    }
    
    // The list can have like 1K ~ 2K items...
    suspend fun emitTransactions(
        defaultDispatcher: CoroutineDispatcher,
        maxTransaction: Double,
        transactions: List<TransactionRate>,
        canvasWidth: Float,
        canvasHeight: Float,
        dots: (start: Offset, end: Offset) -> Unit
    ) {
    	// ... Do some heavy computation for creating the start and end Offset...
        withContext(defaultDispatcher) {       
            transactions.forEachIndexed { index, transactionRate ->           
                dots(Offset(x, y), Offset(x, y)) 
            }
        }
    }
    :thread-please: 1
    n
    • 2
    • 5
  • b

    Barry Fawthrop

    06/10/2021, 9:21 PM
    Please help. I'm stuck in a endless loop. Gradle Syncs not issue but can't build a test app. e: This version (1.0.0-beta07) of the Compose Compiler requires Kotlin version 1.4.32 but you appear to be using Kotlin version 1.5.10 which is not known to be compatible.     Yet I have.
    buildscript {
        ext {
            compose_version = "1.0.0-beta08"
            kotlin_version = "1.5.10"
        }
    Not sure where it's getting beta07 from I can't find it anywhere in the project
    p
    c
    a
    • 4
    • 8
  • n

    nglauber

    06/11/2021, 12:18 AM
    Let’s see if the community will answer… 😛 https://stackoverflow.com/questions/67929861/fillviewport-behavior-in-jetpack-compose-column
    a
    • 2
    • 3
  • c

    Colton Idle

    06/11/2021, 12:56 AM
    Lets say I have a Composable that represents an input field and this input field has some sort of restriction in what it can take in. It could be
    @Composeable fun MyEmailInputField() { ... }
    @Composeable fun MyPhoneInputField() { ... }
    @Composeable fun MyPasswordInputField() { ... }
    Would you have: 1️⃣ the validation/restriction of chars is built into the Composable 2️⃣ the validation/restriction of chars is built into your "ViewModel"
    1️⃣ 5
    2️⃣ 15
    p
    z
    s
    • 4
    • 4
  • s

    Slackbot

    06/11/2021, 8:46 AM
    This message was deleted.
    👍 1
    a
    s
    +2
    • 5
    • 6
Powered by Linen
Title
s

Slackbot

06/11/2021, 8:46 AM
This message was deleted.
👍 1
a

Albert Chang

06/11/2021, 9:24 AM
Agreed. The fact that you must specify an initial value when calling
collectAsState()
on a
Flow
also brings out this problem.
➕ 1
s

streetsofboston

06/11/2021, 11:42 AM
Since both sources of the combine are StateFlows, the resulting combine always has some current value. Would this not work?
suspend fun doSomethingScary1() {
   if (!canDoSomethingScary.first()) return
   // do something scary
}
instead of using
stateIn
?
c

Colton Idle

06/11/2021, 12:11 PM
🤦
k

Kirill Vasilenko

06/11/2021, 1:30 PM
@streetsofboston, yes, you can, but it will still be suspended that is extra here.
s

streetsofboston

06/11/2021, 1:31 PM
True, I though that'd be fine, since the calling function
doSomethingScary1
is suspend as well.
k

Kirill Vasilenko

06/11/2021, 1:32 PM
I will remove this post and you can ask your questions in #coroutines channel or, that is better, on GitHub.
View count: 4