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

    Louis

    08/30/2022, 2:53 PM
    Hey, have you an idea how to reduce the delay for triggering a long press detected by compose ? Ideally i would like it to be 100ms or something like that. I tried using combinedClickable and detectTapGestures but with no really success.
    a
    • 2
    • 2
  • d

    dimsuz

    08/30/2022, 3:36 PM
    I have this in design mockups. How would I go about adding white background to the text? I have tried doing two
    Text
    composables in the
    Box
    , with the former having
    + 1.sp
    , but it doesn't align as perfectly as in the screenshot.
    a
    s
    +2
    • 5
    • 12
  • m

    Moritz Post

    08/30/2022, 3:52 PM
    hi. somewhere i heard about Flow.collectAsState with an "InLifecycle" or "OnLifecycle" appended. It is preferred to the regular collectAsState. Anybody has more infos on it?
    m
    • 2
    • 5
  • a

    Afzal Najam

    08/30/2022, 4:45 PM
    Seems like a noob question but can someone tell me why it would be bad to pass an activity to a screen/top-level Composable (one that already takes a ViewModel for instance, so it’s not skippable)?
    s
    f
    • 3
    • 7
  • h

    Hasan Nagizade

    08/30/2022, 7:06 PM
    is there an article about best practices for compose navigation? Should I do navigation in seperate composable or should I pass navController to viewmodel and do the navigation from there? What is the recommended way?
    k
    g
    • 3
    • 2
  • m

    Marko Novakovic

    08/30/2022, 7:18 PM
    is this Compose idiomatic? to convert this:
    @Composable
    fun Example() {
        Row(modifier = Modifier.fillMaxWidth()) {
            Text(
                text = "Left",
                modifier = Modifier.weight(1f),
            )
            Text(
                text = "Right",
                modifier = Modifier.weight(1f),
            )
        }
    }
    to:
    @Composable
    fun Example(
        left: @Composable (Modifier) -> Unit,
        right: @Composable (Modifier) -> Unit,
        modifier: Modifier = Modifier,
    ) {
        Row(modifier = modifier.fillMaxWidth()) {
            left(Modifier.weight(1f))
            right(Modifier.weight(1f))
        }
    }
    am asking because of passing
    Modifier
    to parameter `@Composable`s. I want to hide
    Modifier.weight(1f)
    and I want everything using
    Example
    to have exactly 2 elements that occupy 50%/50% of space, without wrapping
    left
    and
    right
    into
    Box
    , for example, and applying
    Modifier.weight(1f)
    to
    Box
    container
    f
    a
    • 3
    • 11
  • o

    Othman El Jazouli

    08/30/2022, 9:29 PM
    hey folks, I’m using
    NestedScrollConnection
    as part of a collapsable view with LazyColumn work,
    Box(
            modifier = Modifier
                .fillMaxSize()
                .nestedScroll(nestedScrollConnection)
        ) {
            LazyColumn ..
    
            CollapsingView..
        }
    the idea is I want to get notified when user stops scrolling + they no longer interact with view,
    onPostScroll
    unfortunately is fired when scrolling stops regardless if I still have my finger down, any idea if there is a workaround?
    s
    • 2
    • 2
  • l

    Luke

    08/31/2022, 2:49 AM
    Hello everyone! Does compose support ViewPager with Paging3?
    • 1
    • 1
  • f

    fengdai

    08/31/2022, 3:18 AM
    After upgrading Compose from 1.2.1 to 1.3.0-beta01. This code can cause crash in release build even minify is disabled.
    LineHeightStyle(
      alignment = LineHeightStyle.Alignment.Center,
      trim = LineHeightStyle.Trim.None
    )
    with this error message:
    java.lang.NoSuchMethodError: No virtual method getCenter-PIaL0Z0()I in class Landroidx/compose/ui/text/style/LineHeightStyle$Alignment$Companion; or its super classes
    c
    h
    • 3
    • 8
  • j

    Ji Sungbin

    08/31/2022, 3:28 AM
    Hi, my composable is moving the offset, but the background color is not moving. If I look in the layout inspector, I can clearly see that the offset has been moved. But the background color is still displayed at the old offset. What’s the problem?
    @Composable
    private fun QuackSelectedTabUnderBar(
        modifier: Modifier = Modifier,
        color: QuackColor,
        offsetProvider: Density.() -> IntOffset,
        widthProvider: Density.() -> Dp,
    ) {
        val density = LocalDensity.current
    
        Box(
            modifier = Modifier
                .offset(offset = offsetProvider)
                .then(other = modifier)
                .height(height = QuackTabUnderBarHeight)
                .width(width = density.widthProvider())
                .background(color = color.value)
        )
    }
    I used
    Modifier.offset(offset: Density.() -> IntOffset)
    for moving offset.
    f
    b
    • 3
    • 5
  • a

    AmrJyniat

    08/31/2022, 7:26 AM
    I see that
    LazyColumn
    crops half of its last item, am I missing anything? Code in 🧵
    k
    t
    +3
    • 6
    • 15
  • i

    iroyo

    08/31/2022, 12:31 PM
    After having some recomposition problems with a List I started to look into the Compose Compiler reports and even though I have changed every single list to ImmutableList the reporting still gives me a weird result. A
    Post
    is (in theory) stable but a ImmutableList of Post is not... Am I missing something?
    stable class Post {
      stable val id: String
      stable val title: String
      stable val subtitle: String
      stable val description: String
      stable val tags: ImmutableList<String>
      stable val imageUrl: String
      stable val type: PostType
      <runtime stability> = 
    }
    the strange thing is the empty “<runtime stability>” then I wrap this into a sealed with 3 states (this is for extra context but not directly related)
    stable class Content {
      stable val showError: Boolean
      stable val tags: ImmutableList<Tag>
      unstable val posts: ImmutableList<Post> <------- ?¿?¿?¿
    }
    the Compose result is:
    restartable scheme("[androidx.compose.ui.UiComposable, [_]]") fun DiscoverList(
      stable scrollState: LazyGridState
      unstable items: ImmutableList<Post> <-------- ?¿?¿
      stable onItemViewed: Function2<Post, Int, Unit>
      stable onItemClicked: Function2<Post, Int, Unit>
      stable header: Function2<Composer, Int, Unit>
    )
    Post is a simple data class… is it because it has a List of Strings?
    z
    s
    j
    • 4
    • 13
  • n

    nuhkoca

    08/31/2022, 12:37 PM
    Hello, I use Accompanist Pager but it looses the state of screens. I researched a bit and ran into this issue. And a related issue on IssueTracker is still empty. Did anybody here face a similar issue at all?
    i
    c
    • 3
    • 6
  • a

    Alan Lee

    08/31/2022, 3:44 PM
    What is a recommended way to handle a variable that is only used for the very first composition and changed to null so it is not used again. But changing to null causes the recomposition so trying to find a good way to avoid this.
    h
    m
    • 3
    • 8
  • m

    Marco Pierucci

    08/31/2022, 4:19 PM
    Hello! Does anyone have any idea at where should I start looking when getting:
    Fatal Exception: java.lang.IllegalStateException: LayoutCoordinates androidx.compose.ui.node.InnerPlaceable@25c38a is not attached!
    Im stuck with compose 1.0.5 and whenever I try to update (1.2.0-rc02 and accompanist 0.24.12-rc) crashes start popping into firebase. I have some Integration test running ok, and cant even reproduce locally but the amount of crashes in FB is significant to ignore. The stack-trace ( Full in 🧵 ) does not helps ( at least to mee)
    • 1
    • 1
  • a

    Aaron Waller

    08/31/2022, 5:20 PM
    Is Jetpack Compose not optimized for big projects? I tried now for 1 1/2 Weeks to get my performance right but didn’t succeed. Now I finally figured out that it has something to do with the sheer size of my project. When I simply comment out the the call to my MainScreen() inside the setContent{} method and put in some different code (for example Horizontal Pager + Tab Layout + LazyVerticalGrid) it performs worse in my big project than in a freshly created one even though it is running the exact same code. Only difference is that the laggy project has hundreds of other classes in it (which are not getting called cause I commentet out the call to MainScreen) and a lot more dependencies. Running both projects in Release + R8 enabled So as stupid as it sounds but I just simply have to give up on Jetpack Compose and get back to XML… I’m loosing hope
    l
    r
    z
    • 4
    • 4
  • s

    Susheel

    08/31/2022, 8:31 PM
    Does anyone know if there’s a way to make all the items in a row have the same height as the tallest item in compose? I could use a SubcomposeLayout but not sure if there’s a simpler way
    f
    c
    • 3
    • 5
  • r

    Roudy Korkis Kanaan

    09/01/2022, 3:28 AM
    I'm using Compose Coil for image loading in my project, I have a grid of images shown in my composable and they're driven by a state that would update the grid to another set of images. I'm using Coil with this image loader
    val imageLoader = remember {
        ImageLoader.Builder(context)
            .bitmapFactoryMaxParallelism(10)
            .respectCacheHeaders(false)
            .build()
    }
    (I was playing around the bitmap parallelism and cache headers, I also tried providing disk/cache policies and enabling them in the
    ImageRequest
    but it seems like Coil is quite slow to load the images after they are cached. I tried my same code but use picasso-compose and the images load instantly (After being cached) whereas using Coil there's a split second load, I added a debugger to Coil to make sure it's not loading the image again from the internet (and it's not) The above was on production build for both Coil and Picasso Has anyone experience some performance issues with Coil in Compose?
    c
    c
    • 3
    • 29
  • s

    svenjacobs

    09/01/2022, 5:25 AM
    Jetpack Compose stability in a KMM project I’m currently writing a KMM application where I use Jetpack Compose on the Android side. Of course most of the business logic, the ViewModels and data classes are placed in the
    shared
    module under
    commonMain
    . Now I have the problem that the Compose compiler determines all of my (immutable) data classes as unstable because they are placed in a different module. I cannot add the Compose runtime dependency to
    commonMain
    because this is not a multiplatform dependency and the project just won’t compile when doing so. Of course I could add wrapper classes like described in the linked article and use them only for Android, but this would mean I would have to start using generic types in my ViewModels extensively to ensure that I still share most of the business logic. Isn’t there another way of telling the Compose compiler which classes are actually immutable/stable, maybe via command line arguments or a configuration similar to ProGuard/R8? I’m using version
    1.3.0
    of Compose compiler.
    j
    s
    +2
    • 5
    • 12
  • m

    Mohan manu

    09/01/2022, 5:26 AM
    With Horizontal view pager from accompanist lib it’s not possible to to get individual view model per pager , is there any solution or workaround for this ? Thanks in advance
    a
    • 2
    • 1
  • h

    Hasan Nagizade

    09/01/2022, 7:08 AM
    Unfortunately Jetpack Compose is not as stable as advertised. I have 3 weird glitches in the app and one can only guess what the reason could be. I decided to go back to fragments
    y
    s
    +3
    • 6
    • 5
  • a

    Ali Albaali

    09/01/2022, 12:01 PM
    I have two texts inside a
    Row
    . I want each of them to fill all the available space, when their size isn’t equal (one small, one large), but apply
    Modifier.weight(1F)
    when both are large, so they would extend to the next line. Any thoughts on how to achieve that?
    s
    • 2
    • 4
  • c

    coolchandrakumar

    09/01/2022, 1:01 PM
    Have gone through this issue, https://issuetracker.google.com/issues/240016022 I am looking for another possibility as follows,
    LazyColumn {
                    items(10) {
                        CustomLookAheadLayout {
                              Text(text = "First Item")
                              Text(text = "Second Item")
                        }
                    }
                }
    Still I get error. Is this yet to support ?
    r
    • 2
    • 1
  • r

    Rebecca Franks

    09/01/2022, 1:46 PM
    In general, blurring is an expensive operation, so animating it is probably not the most efficient thing you can do 😄 You could try using Modifier.graphicsLayer and setting a render effect to use blur, and only apply the modifier to the content below. This only works on 31+ though
    @RequiresApi(Build.VERSION_CODES.S)
    fun Modifier.blur(): Modifier = then(
        graphicsLayer {
    
            renderEffect = RenderEffect.createBlurEffect(10f, 10f, Shader.TileMode.CLAMP)
                .asComposeRenderEffect()
        }
    )
    • 1
    • 2
  • d

    dazza5000

    09/01/2022, 2:14 PM
    I wrote up a more concise Stackoverflow post for this issue here: https://stackoverflow.com/questions/73570553/how-to-prevent-accessibility-focus-from-moving-to-controls-behind-texposeddropdo
    • 1
    • 2
  • j

    jayteealao

    09/01/2022, 2:52 PM
    I want to apply an offset to the visible items in a lazy column based on their position in the layout container. I can get the visibleItemInfo from lazylistscrollstate which contains their offset to the top but having extreme difficulties with passing the changing offset to the visible items as the list scrolls
  • c

    Chris Fillmore

    09/01/2022, 3:19 PM
    I’m going through some design review and fixing up inconsistent design. Honestly my UI code is a bit of a mess in this regard; padding, for example, is applied inconsistently, all over the place, as I’ve been just patching things together. So I’d like to build some reusable components to get it into a more consistent state. Can I ask for feedback on my approach?
    f
    • 2
    • 18
  • z

    ziv kesten

    09/01/2022, 3:41 PM
    Does anyone know of any reason
    BackHandler
    might not be intercepting back press? I am using it in a fragment:
    @AndroidEntryPoint
    class MyFragment : BaseFragment() {
    
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return ComposeView(requireContext()).apply {
                setContent {
    
                BackHandler {
                        // not called when back press
                       someAction()
                }
            }
    c
    • 2
    • 2
  • a

    Aaron Waller

    09/01/2022, 3:50 PM
    Is having janky frames normal with Jetpack Compose? I build two test apps, one in Compose and one in XML with a TabLayout + HorizontalPager and a GridView with 3 Columns. I recorded the stacktrace of both apps and uploaded it to Perfetto. The one with many janky frames is jetpack compose. The lags appear while swiping through the HorizontalPager, scrolling through the LazyVerticalGrid is working fine. I think I either have to stop using HorizontalPager + LazyVerticalGrid or switch back to XML. Any ideas what could cause this many janky frames? Code is in Thread ->
    r
    i
    b
    • 4
    • 23
  • j

    Jasmin Fajkic

    09/01/2022, 5:48 PM
    I have hard time ( as a new guy to android and JC) to understand why I can not get update from stateflow into my composable. Code in thread
    s
    • 2
    • 19
Powered by Linen
Title
j

Jasmin Fajkic

09/01/2022, 5:48 PM
I have hard time ( as a new guy to android and JC) to understand why I can not get update from stateflow into my composable. Code in thread
This is my session manager interface
interface SessionManager {
    val currentProfileComplete: Boolean
    val hasSavedProfile: Boolean
    val session: Session

    fun killSession()
    fun saveProfile(profile: ProfileResponse?)
    suspend fun getCurrentUserId(): Resource<Int>?
}

data class Session(
    var profile: ProfileResponse?,
    var isAuthenticated: Boolean,
)
This implementation of SessionManager
class SessionManagerImpl @Inject constructor(
    private val credentialsManager: CredentialsManager,
) : SessionManager {

    private var _session = MutableStateFlow(Session(null, false))
    override val session = _session.asStateFlow().value

    override fun killSession() {
        credentialsManager.removeCredentials()
        _session.update { it.copy(profile = null, isAuthenticated = false) }
    }

    override fun saveProfile(profile: ProfileResponse?) {
        Log.d("Prof", profile.toString())
        _session.value = Session(profile, isAuthenticated = true)
    }

    override suspend fun getCurrentUserId(): Resource<Int>? {
        return when (val userId = credentialsManager.getUserIdFromToken()) {
            is Resource.Success -> userId
            is Resource.Error -> null
            else -> null
        }
    }

    override val hasSavedProfile = session.profile != null

    override val currentProfileComplete =
        hasSavedProfile && (session.profile?.status != null || session.profile?.status === "completed")

}
And in MainActivity i get SessionManager and pass it down to child but it actually never change data
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    @Inject
    lateinit var sessionManager: SessionManager

    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        val intent = Intent()

        FirebaseApp.initializeApp(this)
        Firebase.dynamicLinks
            .getDynamicLink(intent)
            .addOnSuccessListener(this) { pendingDynamicLinkData: PendingDynamicLinkData? ->
                if (pendingDynamicLinkData != null) {
                    intent.data = pendingDynamicLinkData.link
                    this.startActivity(intent)
                }
            }
            .addOnFailureListener(this) { e -> Log.w(TAG, "getDynamicLink:onFailure", e) }

        setContent {
            PhoenixTheme {
                BottomTabView(sessionManager)
            }
        }
    }
}
what I am doing wrong 😞
s

Stylianos Gakis

09/01/2022, 5:53 PM
override val session = _session.asStateFlow().value
I think it's there. You're assigning the initial value of
_session
into
session
and that's it, you never change that
j

Jasmin Fajkic

09/01/2022, 5:54 PM
Hmm probably. Any idea how to solve this properly?
s

Stylianos Gakis

09/01/2022, 5:55 PM
Yeah don't call .value on it and expose it as a StateFlow instead and convert it into state in your composable instead with .collectAsState(WithLifecycle)
Try that for now and see if it fixes the problem and.you can go from there.
j

Jasmin Fajkic

09/01/2022, 5:56 PM
So initially to do this ?
interface SessionManager {
    val currentProfileComplete: Boolean
    val hasSavedProfile: Boolean
    val session: StateFlow<Session>

    fun killSession()
    fun saveProfile(profile: ProfileResponse?)
    suspend fun getCurrentUserId(): Resource<Int>?
}

data class Session(
    var profile: ProfileResponse?,
    var isAuthenticated: Boolean,
)
Same 😞 . I get initial value always.
s

Stylianos Gakis

09/01/2022, 6:01 PM
How are you collecting the value?
j

Jasmin Fajkic

09/01/2022, 6:01 PM
val session = sessionManager.session.collectAsState()
s

Stylianos Gakis

09/01/2022, 6:04 PM
Try debugging by hardcoding your session to be smth like
session =
flow { while(true) { emit(smth); delay(500); emit(smthElse); delay(500); } }.stateIn(...)
And see if this updates your UI.
j

Jasmin Fajkic

09/01/2022, 6:27 PM
this is thing i do not get it. My loginviewmodel get in constructor sessionmanager and when i access session manager through viewmodel it works. when i access it through composable params it does not work.
@Composable
fun Login(navigateToMain: () ->Unit, sessionManager: SessionManager) {
    val loginViewModel: LoginViewModel = hiltViewModel()
    val loginState = loginViewModel.loginState.collectAsState().value

    val session = sessionManager.session.collectAsState()
    val session1 = loginViewModel.sessionManager.session.collectAsState()
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(session.value.isAuthenticated) {
        if(session.value.isAuthenticated) {
            navigateToMain()
        }
    }
    Log.d("ISAUTH1", session.value.toString())
    Log.d("ISAUTH2", session1.value.toString())
so second one works fine first does not react on update 😞
I am thinking that in this case even my session manager is Singleton i get two different SessionManagers in LoginViewModel and MainActivity and because from LoginViewModel I am doing some updates of session it works there and not from MainActivity. @Stylianos Gakis what you think?
Here is how I set session manager with DI
@Module
@InstallIn(SingletonComponent::class)
object SessionManagerModule {

    @Provides
    fun providesSessionManager(
        credentialsManager: CredentialsManager,
    ): SessionManager =
        SessionManagerImpl(credentialsManager)

}
Just put this and all works fine
@Provides
@Singleton
fun providesSessionManager(
    credentialsManager: CredentialsManager,
): SessionManager =
    SessionManagerImpl(credentialsManager)
s

Stylianos Gakis

09/01/2022, 8:41 PM
Yeap without the singleton annotation you would indeed not get the same instance. Glad you figured it out after all ☺️
View count: 8