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
android
  • j

    james

    06/16/2022, 11:06 PM
    this might seem like a silly question, but does anyone know if, using Android Studio (or plain old Gradle) I can isolate Kotlin warnings? the context here is we have an extremely large project with many warnings from both Kotlin and Java, and I’d like to isolate the Kotlin-only warnings. I know I could do this by writing a script to grep only *.kt files, but I figured there might be something built in I can use to do this
    g
    • 2
    • 1
  • h

    hfhbd

    06/18/2022, 8:15 AM
    Is this behavior expected? I would expect printing
    1.8
    instead.
    plugins {
        kotlin("android") version "1.7.0"
        id("com.android.application") version "7.2.1"
    }
    
    android {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }
    
    tasks {
        withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
            println(kotlinOptions.jvmTarget) // prints null
        }
    }
    c
    • 2
    • 4
  • y

    yousef shaaban

    06/18/2022, 3:21 PM
    is there way write
    transient
    final
    int
    m = 50;
    i want to map this line at kotlin Not use
    companion object
    m
    • 2
    • 3
  • r

    Rahul Gill

    06/19/2022, 3:10 AM
    How to keep data stores values in memory for use. Currently I'm having data store values as StateFlow in GlobalScope and then using the values for the api by providing them in lambda
    ktoClient(someHeaderValue: ()->String)= HttpClient{
      ...
      defaultConfig{
        header("headerKey", someHeaderValue())
      }
    }
  • t

    Tin Tran

    06/20/2022, 2:41 AM
    Hi. I’m seeing this crash popping up a lot in my crashlytic board. Does anyone having the same issue? Crash happened mostly in background state
    Fatal Exception: java.lang.IllegalStateException: Not implemented
           at androidx.work.CoroutineWorker.getForegroundInfo$suspendImpl(CoroutineWorker.java:100)
           at androidx.work.CoroutineWorker.getForegroundInfo(CoroutineWorker.java:6)
           at androidx.work.CoroutineWorker$getForegroundInfoAsync$1.invokeSuspend(CoroutineWorker.kt:134)
           at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
           at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
           at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:571)
           at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
           at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
           at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
    My work manager dependency is
    implementation 'androidx.hilt:hilt-work:1.0.0'
        kapt 'androidx.hilt:hilt-compiler:1.0.0'
        implementation "androidx.work:work-runtime-ktx:2.7.1"
    :not-kotlin: 2
  • t

    Tim Malseed

    06/20/2022, 4:32 AM
    Hey friends. We’re looking at hooking into the instrumented tests on Android, to receive realtime progress. We’re able to do this with regular unit tests by attaching a Gradle TestListener. However, instrumented tests don’t use the same Gradle APIs. I’m wondering how Android Studio is able to get realtime test results when running the
    connectedDebugAndroidTest
    task? We can attach a custom Junit
    RunListener
    via gradle
    testInstrumentationRunnerArguments
    - but this passes progress back to the app’s process itself, rather than our local machine.
    :not-kotlin: 1
  • e

    Elnur Jeksenov

    06/20/2022, 8:53 AM
    Hi guys! I want to disable screen recording in my app(screen capture allowed). As I researched on the internet there is only one solution:
    window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
    is there any other solution?
    :not-kotlin: 3
  • t

    Tim Malseed

    06/20/2022, 1:30 PM
    Are the 'not Kotlin' emojis really necessary? I'm happy to help answer questions loosely related to Android dev in this channel, whether they directly involve Kotlin or not. Surely I'm not the only one? We have an amazing wealth of knowledge here, and it seems a shame to turn questions away just because they don't strictly relate to the language. It seems to me that there's no harm in asking..
    🚔 2
    :not-kotlin: 5
    e
    k
    +2
    • 5
    • 8
  • k

    kotlinforandroid

    06/21/2022, 11:50 AM
    I want to periodically read the value of the stepcounter sensor using a
    androidx.work.Worker
    . However, reading the value requires me to register a callback. How do I make my worker wait for the callback to return once without using a busy-loop? Is there a builtin way?
    JobService
    has a dedicated
    finishJob
    method that one could call from the callback.
    androidx.work
    seems to not have this
    class MyWorker(sm: SensorManager, sensor: Sensor, context: Context, params: WorkerParameter): Worker(context, params) {
        private flag: Boolean = false
    
        override fun doWork(): Result {
            sm.registerListener(object : SensorEventListener {
                override fun onSensorEvent(e: SensorEvent) {
                    flag = true
                    // use value...
                }
            }, sensor, TIMEFRAME_FASTEST)
            
            while (!flag) {  }
            return Result.success()
        }
    }
    :not-kotlin: 1
    a
    c
    g
    • 4
    • 6
  • s

    samp

    06/21/2022, 9:14 PM
    Cross posting this question: https://kotlinlang.slack.com/archives/C09222272/p1655845993785259 My problem is related to this stackoverflow question : https://stackoverflow.com/questions/63478955/refactor-my-java-code-to-replace-attribute-access-to-getters-and-setters
    :not-kotlin: 2
  • s

    Satyam G

    06/22/2022, 2:08 PM
    Hello, I am using the In-App Update feature in Android (Immediate Update). We already have a method of
    appUpdateManager.startUpdateFlowForResult(
        info,
        AppUpdateType.IMMEDIATE,
        parentActivity,
        MY_REQUEST_CODE
    )
    Which triggers the Immediate flow. If you observe here we are passing here the MY_REQUEST_CODE while triggering Update. Once the update is Finished, Cancel we get the callback in OnActivityResult based on that we can take decisions. But we already know onActivityResult is deprecated now and it is recommended to use the Activity Result Api which has a code like
    var resultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                // There are no request codes
                val data: Intent? = result.data
                inAppUpdate?.let {
                    inAppUpdate?.onActivityResult(result.resultCode, data)
                }
            } else if (result.resultCode == AppCompatActivity.RESULT_CANCELED) {
                finish()
            }
        }
    But How to get the request code in this case ??? Can anyone help here ?
    :not-kotlin: 2
    👋 1
    l
    t
    i
    • 4
    • 5
  • e

    Erwin Pandawa5

    06/23/2022, 1:34 AM
    message has been deleted
    ❓ 4
  • s

    Sven Obser

    06/23/2022, 3:09 PM
    Hi everyone, I just realized that
    kotlin.random.Random
    produces the same “random” values with each app start on Android. 😨 Is this expected behavior?
    Log.e { "java.util.Random().nextInt(): ${java.util.Random().nextInt()}" }
    Log.e { "kotlin.random.Random.nextInt(): ${kotlin.random.Random.nextInt()}" }
    Output:
    java.util.Random().nextInt(): -1853486751
    kotlin.random.Random.nextInt(): -351317653
    
    java.util.Random().nextInt(): 1794921748
    kotlin.random.Random.nextInt(): -351317653
    
    java.util.Random().nextInt(): 1849140367
    kotlin.random.Random.nextInt(): -351317653
    e
    k
    • 3
    • 9
  • v

    Vivek Modi

    06/24/2022, 9:06 AM
    Hey guys, I have one string in which I want to split into list from there where I should provide character. I'll explain in details
    For example 1
    val string = "Birth Control"
        
        val searchText = "n"
    Output
    ["Birth Co", "trol"]
    For example 2
    val string = "Bladder Infection"
    
        val searchText = "i"
    Actual Output
    ["Bladder ", "nfect", "on"]
    Expect Output
    ["Bladder ", "nfection"]
    I tried some code but
    example 1
    is working fine but
    example 2
    is not because I only want to split first occurrence.
    val splitList = title?.split(searchText, ignoreCase = true)?.toMutableList()
        splitList?.remove(searchText)
    Can someone guide me how to solve this idiomatic way. Thanks
    t
    • 2
    • 2
  • n

    Nurbanu Kahraman

    06/24/2022, 10:51 AM
    How to stop of android cracked apks?
    🤣 1
    :not-kotlin: 7
    v
    d
    +5
    • 8
    • 17
  • d

    davidbritish

    06/24/2022, 9:34 PM
    Does anybody know of any documentation detailing kotlin components' Min Api? Especially now with kotlin 1.7's removal of the jvmTarget 1.6 option? Seems like existing documentation is only on Kotlin on Android's FAQ page last updated on 2020, and a Stackoverflow post from 2017.
  • r

    rkeazor

    06/25/2022, 2:20 AM
    For those who have Data Classes in public apis. How do you handle Binary and Source Compatibility issues
  • a

    AmrJyniat

    06/25/2022, 5:01 AM
    How to reflect a flow value when it gets ready after collecting?
    var property: String? = null
    .......
    
    propertyFlow.collect{
        property = it
    }
    
    .......
    
    textView.text = property // reflect this value when its get ready
    Something like that, any idea?
    e
    d
    • 3
    • 5
  • b

    brookmg

    06/25/2022, 9:18 AM
    Hey guys, this might be a weird question but is there a way to start a tagged co-routine? To be able to cancel batch of them if a parameter is changed. Is dedicated a job for related tasks the only way to do this?
    j
    • 2
    • 1
  • h

    Hannan Shaikh

    06/26/2022, 12:34 PM
    Hi there, I want to setup Custom Navigation drawer using navigation components, can anyone help me
    :not-kotlin: 9
  • d

    dazza5000

    06/27/2022, 6:22 PM
    has anyone implemented app idle timeout using kotlin and have an implementation strategy they want to share/highlight?
    :not-kotlin: 2
    :kotlin-intensifies: 1
    g
    • 2
    • 3
  • c

    Colton Idle

    06/28/2022, 2:21 AM
    I need to make an api call (suspend function since I use retrofit) in my FirebaseMessagingService. What's the proper way to make a suspend call in an Android service? Does this comment still hold true in 2022? https://stackoverflow.com/a/63407811
    f
    g
    i
    • 4
    • 21
  • m

    Mahesh Kavathiya

    06/28/2022, 5:32 AM
    Hi Everyone, is it possible to change build flavour run time? I wanted to use common build for all environment and select flavour from menu, based on selection data will be updated which is available on each flavours like strings, drawable etc. Currently we are maintaining separate builds for DEV/SIT/UAT, but want to keep single build and QA can select flavours based on their requirement for testing. Any thought process on this? Thanks
    🇳🇴 2
    g
    f
    m
    • 4
    • 11
  • a

    Ali

    06/29/2022, 11:43 AM
    What is the efficient way to modify a list in kotlin? for ex. From this list
    mutableListOf(listOf(1,2,3,4,5), listOf(6,7,8,9,10))
    I need this modified result but keeping original list as it is.
    [[1,2], [6,7,8,9,10]]
    t
    t
    • 3
    • 2
  • a

    Aldup

    06/29/2022, 11:37 PM
    Hello guys I want to push a local notification at a scheduled time eg: everyday at 09:00pm, defined by the user. Either with WorkManager or AlarmManager. Any advice ? Ps: I'm using jetpack compose.
    :not-kotlin: 2
    g
    • 2
    • 2
  • m

    Michael Bichlmeier

    06/30/2022, 8:28 AM
    Hey guys, is someone of you using the play console managed publishing? I have a question about that and hope you can help me
    :kotlin: 1
    :android-dance: 1
    :not-kotlin: 6
    c
    d
    • 3
    • 3
  • r

    Rohan Maity

    06/30/2022, 9:53 AM
    Does Navigation Kotlin DSL (not compose) support actions?
  • m

    Mjahangiry75

    06/30/2022, 11:02 AM
    Is it a bad practice to have a same model for both
    retrofit
    and
    room?
    :not-kotlin: 5
    k
    • 2
    • 1
  • k

    Katarzyna

    06/30/2022, 11:26 AM
    Recently, Mustafa wrote a rule-based validation structure for all my inputs. It’s very flexible and manageable. Today he will try to explain the validator library. Read the article written by Mustafa Yigit. 👇 validator | Rule Based Validation Library in Android | by Mustafa Yiğit | Jun, 2022 | Kt. Academy (kotlin-academy.com)
    k
    • 2
    • 1
  • a

    AmrJyniat

    06/30/2022, 1:18 PM
    How to recollect
    SharedFlow
    when the first collect got exception? like I expose a
    Flow
    from repo to VM then convert it to
    SharedFlow
    by
    shareIn()
    then collect this SharedFlow from the fragment, now I got an exception while collecting the SharedFlow, so how to retry/recollect it again?
    g
    • 2
    • 25
Powered by Linen
Title
a

AmrJyniat

06/30/2022, 1:18 PM
How to recollect
SharedFlow
when the first collect got exception? like I expose a
Flow
from repo to VM then convert it to
SharedFlow
by
shareIn()
then collect this SharedFlow from the fragment, now I got an exception while collecting the SharedFlow, so how to retry/recollect it again?
g

gildor

07/05/2022, 4:14 AM
You should include this recollection logic before converting it to SharedFlow You can use
retry
for this: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/retry.html
But still, I would recommend to handle it on level of original Flow, because it knows better semantics of those errors and have more ways to handle it, so your flow wouldn’t propagate errors, instead ignore errors and retry or emit error state and retry after that So if you control code of original Flow, just handle it there, if not, you can use
retry
But don’t forget, you should use retry before creating StateFlow
a

AmrJyniat

07/05/2022, 7:07 AM
I could use retry on the original Flow like:
flow.retryWhen { cause, attempt -> 
    attempt < 3
}
But I have a button for retrying the API call when failed and, I couldn't handle the retry mechanism when the click event occurred.
g

gildor

07/05/2022, 7:10 AM
BTW, flow.retry(3) will do the same
But user retry is different thing, and probably should be resolved on level of reactive stream, so when you have source (or multiple sources) of event to start loading, it mapped to your request
It hard to recommend particular solution without context
But this doesn’t look as work for retry() at all, but rather matter how you design your data flows
a

AmrJyniat

07/05/2022, 7:20 AM
I receive the Flow from repo to VM like:
val flow: Flow<Result<T>> = repo.getData()
And collect the flow in the fragment, now the retry button appears when the
result
failed, I searched for an elegant/clean way to recollect the flow on the click event, therefore, the API called again but I didn't found. I ended up with something like that:
private val _sponsors = Channel<Unit>()
val sponsors = _sponsors.receiveAsFlow().flatMapLatest {
        repository.loadSponsors()
  }.myShareIn(viewModelScope, replay = 1)

fun loadSponsors() = viewModelScope.launch {
   _sponsors.send(Unit)
}

init { loadSponsors() }
In this case, just call `loadSponsors()`fun when the retry button clicked, what do you think?
g

gildor

07/05/2022, 9:33 AM
so what is your problem with this code?
I’m not exactly sure that I see any problem So you should show error case and allow to reload
Just do not cache failed “repository.loadSponsors”
return some error state instead
like:
val sponsors = _sponsors.receiveAsFlow().flatMapLatest {
        return runCatching {
            repository.loadSponsors())
         } 
  }.myShareIn(viewModelScope, replay = 1)
I use Kotlin Result here, but you can use any own state to propagate error
a

AmrJyniat

07/05/2022, 9:40 AM
I see, thank you man, I just tried to apply the cleanest way.
g

gildor

07/05/2022, 9:47 AM
Otherwise how you can handle error case?
a

AmrJyniat

07/05/2022, 10:10 AM
The
sponsors
val is a flow containing custom Result class
Result<T>
, so when collecting it in the fragment I'm just checking if the result failed or not, therefore, I don't need any processing in the VM like
runCathing{}
because the catch applied already in the repo layer.
g

gildor

07/05/2022, 12:51 PM
So if you already have this Result class, you do not throw exception and no need to restart, right?
a

AmrJyniat

07/05/2022, 12:58 PM
Ok but if the result failed when collecting the flow, how to recall the API? I need to recollect the flow again, that's it.
g

gildor

07/05/2022, 1:51 PM
What kind result?
If loadSponsors will return error?
But in this case you just restart chain by emitting to _sponsors
a

AmrJyniat

07/05/2022, 2:03 PM
Yes in the final solution I retrigger the API call by emitting to _sponsors. But I was hoping to find something built-in like retry() in the Flow Apis to make my code more elegant.
g

gildor

07/05/2022, 3:09 PM
retry exists, it just will not help in this case
View count: 23