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
  • v

    Vitor Prado

    02/22/2021, 7:00 PM
    Is there a way to show items in a row and overflow to a new line? or I need to create a view to do that?
    a
    s
    • 3
    • 2
  • t

    TheMrCodes

    02/22/2021, 7:08 PM
    Is there any way to measure a Composable before drawing without getting the siize aferward with .onSizeChanged?
    v
    t
    n
    • 4
    • 5
  • e

    eygraber

    02/22/2021, 7:38 PM
    Is there a way to react to the progress of AnimatedVisibility? My use case is that I have a list of composable functions, and I want to animate additions and deletions to it, so I'm wrapping each item in an AnimatedVisibility. The problem as I understand it is that I can't delete a function from the list until the transition is finished (because then it won't get composed anymore; is that the proper terminology?). My idea is to mark the item as deleted, and remove it once the transition is complete, but I'm not 100% sure how to do that.
    d
    k
    • 3
    • 2
  • c

    Chris Grigg

    02/22/2021, 9:58 PM
    Has anyone run into this? I posted it on Stack Overflow a couple weeks ago and nobody had anything to say https://stackoverflow.com/questions/66126551/jetpack-compose-centering-text-without-font-padding
    a
    • 2
    • 5
  • c

    Colton Idle

    02/22/2021, 11:23 PM
    Hello! My team has a custom type scale and therefore we're not using the material type system. Is there anything wrong with this code or is this pretty much how you set it up?
    private val Lato = FontFamily(
        Font(R.font.lato_regular, FontWeight.Normal),
        Font(R.font.lato_bold, FontWeight.Bold),
    )
    
    object MyTypeSystem {
        val head = TextStyle(
            fontFamily = Lato,
            fontSize = 18.sp,
            fontWeight = FontWeight.Normal
        )
        val body = TextStyle(
            fontFamily = Lato,
            fontSize = 12.sp,
            fontWeight = FontWeight.Bold
        )
    ...
    }
    j
    s
    b
    • 4
    • 3
  • e

    eygraber

    02/23/2021, 6:48 AM
    Is there a way to
    remember
    something mutable, but not cause a recomposition when it is mutated?
    l
    j
    s
    • 4
    • 7
  • k

    krzysztof

    02/23/2021, 8:13 AM
    Is there a way to capture (any) touch event at parent level, so that child composables are not reacting to it?
    s
    • 2
    • 3
  • d

    Dieter Holz

    02/23/2021, 8:50 AM
    loadImageResource is deprecated since alpha12. What’s the proper replacement? Does painterResource load the image in background?
    n
    • 2
    • 2
  • s

    Shakil Karim

    02/23/2021, 9:53 AM
    I'm trying to use popUpTo with Navigating with Compose.
    popUpTo(Destination.OnboardingWelcomeScreen.route) { inclusive = true }
    But it giving me error because it's expecting int instead of String.
    p
    • 2
    • 2
  • k

    Kevin Aude

    02/23/2021, 10:57 AM
    Hi all, I’m wondering if there are any good examples out there showing how to load things off the main thread from inside a composable
    m
    c
    a
    • 4
    • 9
  • k

    Kevin Aude

    02/23/2021, 10:58 AM
    My use case is: I pass a ResolveInfo object to my composable function and load an app name and icon from inside that composable, at the moment it’s super slow
    j
    • 2
    • 5
  • d

    Deepak Gahlot

    02/23/2021, 10:59 AM
    Is there a way in LazyColumn to scroll to a particular position in an Item. I'm working on building Expandable Item List. And each Expandable Card contains multiple Questions that user has to fill the answer. Once the user submit the answer, I check the validations from server and show the error is respective answer. Now i need a way to scroll to that particular answer and then keep on moving to the next error. Before COMPOSE i used to do this via requestFocus using a recyclerview. i have been going through documentation of compose and unable to find a way to build this
    s
    d
    +2
    • 5
    • 20
  • d

    Deepak Gahlot

    02/23/2021, 11:00 AM
    I understand that there is a way to scroll to the item, but nothing if need to scroll to a particular content in that item(Expandable vIEW)
    a
    • 2
    • 2
  • y

    Yuri Drigin

    02/23/2021, 12:13 PM
    Why
    onCommit
    crashed with
    Composition re quires an active composition context
    ?
    @Composable
    fun NetworkImage(
    		modifier: Modifier,
    		url: String?,
    		placeholder: Int
    ) {
    		var image by remember { mutableStateOf<ImageBitmap?>(null) }
    
    		onCommit {
    				val picasso = Picasso.get()
    z
    • 2
    • 5
  • a

    Archie

    02/23/2021, 1:00 PM
    Hi, is there a way to add listener to
    Transition
    ? I'd like to do an action after the new state have been reached something like:
    val transitionState = remember {
        MutableTransitionState(false)
    }
    
    val transition = updateTransition(transitionState)
    val scale by transition.animateFloat(
        transitionSpec = { spring(dampingRatio = Spring.DampingRatioMediumBouncy) }
    ) {
        when (it) {
            true -> 1f
            false -> 0f
        }
    }
    
    LaunchedEffect(viewModel, navController) {
       delay(1000)
       transitionState.targetState = true
       // Then I want to do an action after the animation finished
       // but I can't find a way to attached a listener to Transition.
    }
    j
    b
    • 3
    • 6
  • s

    Sergey Y.

    02/23/2021, 1:50 PM
    Hi, I am working on some functionality in our application that requires the render of single-stroke fonts for cutting. Unfortunately android cannot display such fonts correctly, so we use the
    Freetype Harfbazz
    library to render individual glyphs as a sequence of vector paths. Now I'm looking for an option how this can be integrated into the pipeline of the standard android input system, and with the Compose(I'm considering CoreTextField). In the case of working with a regular
    EditText
    , it seems to me that I will need to rewrite everything from scratch(cursor, line break, context menu, text selection, etc.). But since the Compose has platform(android, desktop) implementations of text input, that means it uses abstractions around working with text. Which means it is should be possible to change implementation. I found an abstraction like Paragraph and its platform implementation for Android AndroidParagraph, which under the hood uses the TextLayout wrapper for StaticLayout class. And a MultiParagraph class that uses the above Paragraph. I would like to replace the implementation for the
    AndroidParagraph
    with my own but it seems that I do not see how this could be done. I would be apprecited any help. Thanks.
    j
    s
    • 3
    • 4
  • m

    Mehdi Haghgoo

    02/23/2021, 2:18 PM
    Animation APIs in Compose seem very complicated. I literally don't understand any of what the inline docs say!
    k
    b
    +4
    • 7
    • 12
  • d

    Daniele B

    02/23/2021, 6:18 PM
    I realized there is a lot of confusion about the concept of “*Single Source Of Truth*”. In traditional Android development, we used to talk about SSoT in the context of the Repository. Can we please agree, and probably make it clear, that the SSoT in the context of JetpackCompose (and DeclarativeUIs), has nothing to do with the Repository (and the DataLayer), but only with the ViewModel? I keep hearing developers saying that the SSoT of an app is the DB, even in the context of JetpackCompose. How does that make sense? I am attaching a diagram, where I try to highlight the difference between AppState (which is part of the ViewModel) and Repository (which is part of the DataLayer), with particular reference to the D-KMP architecture. Any comment is very welcome.
    j
    j
    +2
    • 5
    • 24
  • m

    Mikołaj Kąkol

    02/23/2021, 7:25 PM
    it seams that
    rememberSaveableStateHolder
    is broken in somehow in alpha12. Consider example from here: https://github.com/androidx/androidx/blob/androidx-main/compose/runtime/runtime-sa[…]/compose/runtime/saveable/samples/SaveableStateHolderSamples.kt and change
    Box(modifier) {
                restorableStateHolder.SaveableStateProvider(currentScreen) {
                    content(currentScreen)
                }
           }
    to
    Box(modifier) {
                restorableStateHolder.SaveableStateProvider(currentScreen) {
                    Crossfade(targetState = currentScreen) {
                        content(it)
                    }
                }
            }
    you will notice that animation doesn’t work. If you will remove that state holder:
    Box(modifier) {
                Crossfade(targetState = currentScreen) {
                    content(it)
                }
            }
    crossfade works. So either
    stateholder
    is broken or
    crossfade
    . From what I unsderstand problem is that Crossfade implementation uses
    remember
    to store items to render during transition. What I wanted to achieve is some nice animation between screens. What to do? 🤔 🙀
    a
    a
    • 3
    • 7
  • u

    utikeev

    02/23/2021, 7:36 PM
    I've implemented custom Pager based on this implementation, but also supporting zoom and vertical pan for alpha11. In alpha12
    DragObserver
    got deprecated, but I didn't manage to properly migrate my implementation to new API. Using two
    draggable
    modifiers prevents from dragging simultaneously in both directions and zooming at the same time, while using
    pointerInput
    lacks was kind of tricky: •
    detectDragGestures
    lack
    onStart
    and
    velocity
    parameter in
    onEnd
    callback •
    drag
    function seems to allow more fine-grained setting up, but judging by
    detectDragGestures
    is also quite hard to handle. Also
    velocity
    has to be calculated somehow (isn't really clear) I'll attach deprecated snippet, which I currently use, and would be glad to know several directions on how it can be implemented with new API with the similar amount of code.
    a
    m
    +2
    • 5
    • 9
  • k

    Ky

    02/23/2021, 11:05 PM
    Hi, my BasicTextField composable and
    adjustPan
    are not behaving properly after the first focus. The first click, the composable is properly moved up but if you close the keyboard and click back into the field, it is now partially obscured by the keyboard. Has anyone run into this?
    s
    • 2
    • 2
  • i

    itnoles

    02/24/2021, 1:51 AM
    How I can do clickable inside of
    items
    for
    LazyColumn
    ?
    v
    • 2
    • 4
  • n

    nanodeath

    02/24/2021, 5:07 AM
    having a rough time trying to get started with 0.3.0 in the tutorials
    a
    • 2
    • 4
  • c

    Chachako

    02/24/2021, 7:23 AM
    Is there a way to update the variables without directly reorganizing them?
    remember { mutableStateOf(...) }
    will be reorganized immediately after each
    setValue
    , but I just want to update the variable, and then manually reorganize and remember this variable at some point. what should I do?
    k
    a
    • 3
    • 3
  • r

    rsktash

    02/24/2021, 8:49 AM
    Everybody is waiting beta 😉
    ➕ 1
    :jetpack-compose: 15
    :yes: 11
    k
    o
    h
    • 4
    • 6
  • e

    eygraber

    02/24/2021, 9:23 AM
    If a sealed class is marked as
    Immutable
    are all of its subclasses considered
    Immutable
    as well?
    👀 1
    j
    • 2
    • 3
  • s

    Smorg

    02/24/2021, 10:12 AM
    Any recommendations for an implementation of Collapsible App bar in compose please?
    j
    • 2
    • 2
  • k

    Karthick

    02/24/2021, 10:15 AM
    Any idea how to create viewmodel scoped to composable function, means it will be destroyed once the function disposes.
    a
    l
    i
    • 4
    • 11
  • r

    Rahul Sainani

    02/24/2021, 10:50 AM
    Is anybody else also stuck with text not being vertically center in buttons, top app bar, etc? Seems a bit towards the top than center.
    c
    o
    c
    • 4
    • 15
  • m

    Manu Eder

    02/24/2021, 11:30 AM
    Hey, I'm new to compose, been reading the documentation. One thing I'm wondering about is, why does the documentation promote passing down state that is to be mutated downstream as two parameters (
    state: T, onChange: (T) -> Unit
    ) instead of a single parameter (
    stateD: MutableState<T>
    ). E.g. why is the
    Checkbox2
    -example below promoted over
    Checkbox1
    . (I know the two are subtly different in when the state that the modification is based on is read.) More generally, I think what I was expecting to find, but haven't seen yet is some standard way to handle what I expect to be a common case of creating some "widget" whose entire state can be described by some (immutable data) class and where "subwidgets" modify part of that state. I.e. I guess I'm looking for a blessed function:
    (MutableState<T>, Lens<T, S>) -> MutableState<S>
    or, with automatic creation of Lenses (https://www.reddit.com/r/Kotlin/comments/4i5wsp/lenses_for_kotlin/):
    (MutableState<T>, KProperty1<T, S>) -> MutableState<S>
    . Does something like this exist? Is there a good reason why it shouldn't?
    Checkbox1
    and
    Checkbox2
    -example:
    @Composable
    fun Checkbox1(stateD: MutableState<Boolean>) {
        var state by stateD
        Button(onClick = {state = !state}) {
            Text( if (state) "on" else "off")
        }
    }
    
    @Preview
    @Composable
    fun UseCheckbox1() {
        val stateD = remember { mutableStateOf(false) }
        Checkbox1(stateD)
    }
    
    @Composable
    fun Checkbox2(stateVal: Boolean, stateChanger: (Boolean) -> Unit ) {
        Button(onClick = {stateChanger(!stateVal)}) {
            Text( if (stateVal) "on" else "off")
        }
    }
    
    @Preview
    @Composable
    fun UseCheckbox2() {
        val stateD = remember { mutableStateOf(false) }
        var state by stateD
        Checkbox2(stateVal = state, stateChanger = {state = it} )
    }
    a
    a
    • 3
    • 8
Powered by Linen
Title
m

Manu Eder

02/24/2021, 11:30 AM
Hey, I'm new to compose, been reading the documentation. One thing I'm wondering about is, why does the documentation promote passing down state that is to be mutated downstream as two parameters (
state: T, onChange: (T) -> Unit
) instead of a single parameter (
stateD: MutableState<T>
). E.g. why is the
Checkbox2
-example below promoted over
Checkbox1
. (I know the two are subtly different in when the state that the modification is based on is read.) More generally, I think what I was expecting to find, but haven't seen yet is some standard way to handle what I expect to be a common case of creating some "widget" whose entire state can be described by some (immutable data) class and where "subwidgets" modify part of that state. I.e. I guess I'm looking for a blessed function:
(MutableState<T>, Lens<T, S>) -> MutableState<S>
or, with automatic creation of Lenses (https://www.reddit.com/r/Kotlin/comments/4i5wsp/lenses_for_kotlin/):
(MutableState<T>, KProperty1<T, S>) -> MutableState<S>
. Does something like this exist? Is there a good reason why it shouldn't?
Checkbox1
and
Checkbox2
-example:
@Composable
fun Checkbox1(stateD: MutableState<Boolean>) {
    var state by stateD
    Button(onClick = {state = !state}) {
        Text( if (state) "on" else "off")
    }
}

@Preview
@Composable
fun UseCheckbox1() {
    val stateD = remember { mutableStateOf(false) }
    Checkbox1(stateD)
}

@Composable
fun Checkbox2(stateVal: Boolean, stateChanger: (Boolean) -> Unit ) {
    Button(onClick = {stateChanger(!stateVal)}) {
        Text( if (stateVal) "on" else "off")
    }
}

@Preview
@Composable
fun UseCheckbox2() {
    val stateD = remember { mutableStateOf(false) }
    var state by stateD
    Checkbox2(stateVal = state, stateChanger = {state = it} )
}
a

allan.conda

02/24/2021, 12:11 PM
composable with mutablestate is stateful, the other approach is to make the composable stateless. Read more here https://developer.android.com/jetpack/compose/state
m

Manu Eder

02/24/2021, 12:32 PM
That's the exact page I spent a lot of time looking at and thinking about :-) I'll try to rephrase: For any not-completely-trivial "widget" built with compose which reacts to user interaction there will be "state" somewhere. I typically won't want to "create" the state variable in the widget itself (with
remember { mutableStateOf( ... ) }
), but instead will want to pass it down. The documentation promotes passing down a value and a setter (which is very similar to a getter and a setter). I would like to be able to just say "use this field of this variable that I already have" (which was probably passed down to me, and might again be a field of some other variable), without having to write getters and setters all the time. So, I'd like to be able to have something like
data class TwoBools( val one: Boolean, val two: Boolean )

@Composable fun TwoCheckboxes( state: GetSet<TwoBools> ) {
  Checkbox( state.field(TwoBools::one) )
  Checkbox( state.field(TwoBools::two) )
}

@Composable fun Checkbox( state: GetSet<Boolean> ) {
  ...
}
field
would be a member/extension function of GetSet<T>. And
GetSet<T>
might or might not be equal to
MutableState<T>
.
The type of
field
would be the aforementioned
(GetSet<T>).(KProperty1<T, S>) -> GetSet<S>
I think I can probably write
field
. This just seems like such an obvious pattern that I felt it should probably exist somewhere already. Also, I don't understand the internals of compose and don't know what kind of performance implications the different ways of doing this might have. Should
GetSet<T>
be an interface (i.e. =
MutableState<T>
?), should it be
data class GetSet<T>(get: () -> T, set: (T) -> Unit)
, should it be
data class GetSet<T>(get: T, set: (T) -> Unit)
, etc...?
(Without the proposed field function the
TwoCheckboxes
code above would look like this:
data class TwoBools( val one: Boolean, val two: Boolean )

@Composable fun TwoCheckboxes( state: TwoBools, stateSetter: (TwoBools) -> Unit ) {
  Checkbox( state.one, { stateSetter(state.copy(one=it)) } )
  Checkbox( state.two, { stateSetter(state.copy(two=it)) } )
}

@Composable fun Checkbox( state: Boolean, stateSetter: (Boolean) -> Unit ) {
  ...
}
, which isn't a lot longer, but does get kinda repetitive, and the field name is referenced twice instead of once...)
a

Albert Chang

02/24/2021, 2:13 PM
I think it depends on whether you want to allow your user to control the state change. Taking the current value and a lambda allows the user to prevent the state change under certain conditions, or do something extra when the state changes. On the contrary, if the state change shouldn't be interfered by the user, you should use
MutableState
or something like that.
LazyListState
is a good example. It is essentially a mutable state.
m

Manu Eder

02/24/2021, 3:25 PM
Thanks for the reply 🙂
MutableState<T>
is an interface. Anything that you can do with
currentValue
and
lambdaFun
you can do with `MutableState<T>`:
object : MutableState<Boolean> {
  override operator fun component1() = currentValue
  override operator fun component2() = lambdaFun
  override var value : Boolean
    get() = currentValue
    set(newVal) = lambdaFun(newVal)
}
(And you can make this less verbose if you plan to do it a lot.) I noticed LazyListState as one of the few examples where both getter and setter are passed as one variable. I was just wondering why it wasn't using something like
MutableState<ImmutableLazyListState>
, i.e. why there wasn't some kind of standardized way of doing what LazyListState does.
a

Albert Chang

02/25/2021, 1:21 AM
Though
MutableState
is an interface, it is the
SnapshotMutableStateImpl
class that actually enables the
Recomposer
to subscribe to changes of the value (the subscription relies on the
Snapshot
mechanism). You own implementation of
MutableState
won't have this ability thus automatic recomposition will not work. You can verify this yourself. Besides
LazyListState
, essentially the return types of all
remember*State()
functions are mutable states, such as
ScaffoldState
,
ScrollState
, etc. They contain relatively complex logics and provide the user with extra methods.
View count: 4