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

    zain

    05/28/2021, 2:03 PM
    Need help in converting this into a coroutine 🙂
    nextButton.setOnLongClickListener {
                val handler = Handler(Looper.myLooper()!!)
                val runnable: Runnable = object : Runnable {
                    override fun run() {
                        handler.removeCallbacks(this)
                        if (nextButton.isPressed) {
                            println("Do Something!")
                            handler.postDelayed(this, 500)
                        }
                    }
                }
                handler.postDelayed(runnable, 0)
                true
    }
    r
    1 reply · 2 participants
  • c

    Christian Dräger

    05/28/2021, 9:03 PM
    hey, i have written a little android example app (my first one ever 😄) with jetpack-compose. since i need to use a blocking client to fetch my data to fulfill my use-case i am wondering how to do that. what i tried is to just call my client in a suspend function / coroutine and make the data available to my composables via a viewModel like this:
    class StargazerViewModel : ViewModel() {
    
        private var _users: MutableLiveData<List<User>> = MutableLiveData(emptyList())
        val users: LiveData<List<User>> = _users
    
        fun updateUsers() {
            viewModelScope.launch {
                _users.postValue(fetch())
                // _users.postValue(dummyData) // when using valid dummy data here the app works as aspected
            }
        }
    }
    
    private suspend fun fetch(): List<User> =
        skrape(HttpFetcher) {
            request {
                url = "<https://github.com/skrapeit/skrape.it/stargazers>"
            }
    ...
    full code here: https://github.com/skrapeit/skrape.it/blob/android-example/examples/android/app/src/main/java/it/skrape/skrapeitexample/MainActivity.kt whenever i call the fetch method i get a
    android.os.NetworkOnMainThreadException
    which i assume is because my client call is blocking and thereby break the coroutine (maybe?) what can i do to run the blocking client in a background thread to avoid the NetworkOnMainThreadException in a jetpack-compose project?
    j
    14 replies · 2 participants
  • t

    theapache64

    05/29/2021, 10:50 AM
    ✅ [RESOLVED] Thread: AS can't compile with
    dagger.hilt.android.plugin
    plugin 🧵
    4 replies · 1 participant
  • s

    Sunny

    05/29/2021, 2:00 PM
    Can somebody help, need help in gesture part of jetpack compose https://stackoverflow.com/questions/67752131/long-press-gesture-in-jetpack-compose
    a
    1 reply · 2 participants
  • a

    Aldan Rizki Santosa

    05/29/2021, 3:29 PM
    How to change the field name of
    Pair
    ? The code like this :
    val distributorNotes = ArrayList<PairDistributorNotes<String, String>>()
    
    distributorNotes.add(PairDistributorNotes("350631771", "test"))
    
    data class PairDistributorNotes<out x, out y>(val distributor_id: x, val note: y) {
        override fun toString(): String = "($distributor_id, $note)"
    }
    and i create
    asReverse(
    ) with
    distinctBy
    val dataJson = Gson().toJson(distributorNotes.asReversed().distinctBy { it.distributor_id })
    Output from dataJson :
    [{"a":"350631771","b":"test"}]
    Can field a and b change to distributor_id and note ? Expected :
    [{"distributor_id":"350631771","note":"test"}]
    UPDATE Based on Christian Grach answer, because Proguard is enabled, Gson require annotations to preserve the field name.. We need to add
    @field:SerializedName()
    on
    data class
    data class PairDistributorNotes<out A, out B>(
          @field:SerializedName("distributor_id")
          val distributor_id: A,
    
          @field:SerializedName("note")
          val note: B
    ) {
          override fun toString(): String = "($distributor_id, $note)"
    }
    c
    5 replies · 2 participants
  • m

    Mjahangiry75

    05/30/2021, 9:46 AM
    is there any better way to write this code? code in thread
    d
    u
    3 replies · 3 participants
  • n

    noone

    05/30/2021, 6:12 PM
    does anyone have experience with kmm here?
    u
    2 replies · 2 participants
  • o

    onirutlA

    05/31/2021, 7:39 AM
    Hi guys i use single activity want to ask how to pass data from parent fragment to child fragment, the child fragment attached to parent fragment by tab layout got any reference without creating interface
    :not-kotlin: 2
    s
    f
    3 replies · 3 participants
  • i

    izyaboi

    05/31/2021, 8:34 AM
    I have some problem to bind a viewmodel with the ui logic to a <include> layout i have some <inlude in my layout and i want to pass my viewmodel to all inlude layout? what is the prefered solution? 🤔
    g
    y
    13 replies · 3 participants
  • e

    Emiliano Schiavone

    05/31/2021, 6:00 PM
    Hello, does anyone have this issue with AS Artic Fox on a MacPro using a mac pro with M1 chip?
    :not-kotlin: 3
    c
    c
    +1
    8 replies · 4 participants
  • j

    Jesus Cruz Victoria

    05/31/2021, 9:04 PM
    Hi guys, do U know how I can install 1 app from another app, just like Facebook do with messenger?? https://stackoverflow.com/questions/63812164/how-does-the-facebook-android-app-install-facebook-messenger
    :not-kotlin: 6
    c
    1 reply · 2 participants
  • o

    onirutlA

    06/01/2021, 12:55 AM
    Hello guys need help to how to hide my appbar and bottom nav view when i'm scrolling, the appbar and toolbar is in the fragment and the bottom nav view is in activity and I'm using navigation component so how can i achieve that
    n
    6 replies · 2 participants
  • k

    knthmn

    06/01/2021, 3:43 AM
    I have seen people initialize variables in lifecycle classes by doing this
    class MainActivity : ComponentActivity() {
        
        val foo by lazy { Foo() }
        
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            foo // initialize
        }
    }
    I see the following benefits • the "initialization" of the value is visually closer to where it is defined •
    foo
    is a
    val
    Are there any disadvantages doing this? What do you guys prefer?
    :kotlin-intensifies: 1
    j
    2 replies · 2 participants
  • p

    Pawan Gorai

    06/01/2021, 10:03 AM
    Hello everyone, I have been into kotlin for few months, one issue I started facing in the early days of my learning. I will be very much thankful for any response regarding the same. I have a JSON list, in which I need to filter the data based on some filters. I was using predicate for filtering, but as per my need I need to filter the nested list, and if here I use predicates I am left with 3 test predicates that's
    Any, None, and All
    but as I want only matched data and which I am not getting using any of these predicates. As Any returns true if at least there is one match element, and All returns true if there are all matched elements but how can I get only the matched elements from the nested list irrespective of any non-matched element. I can use the traditional approach of looping through the list, but I wanted to know whether it is possible using a predicate. Here's the sample JSON I am trying to get the center whose session elements contains
    min_age_limit is > 18
    and
    available_dose_1 > 0
    .
    {
    "centers": [
    	{
    		....
    		"sessions": [
    			{
    				"session_id":"adad",
    				...
    				"min_age_limit":45,
    				"available_capacity_dose1": 5,
    				"available_capacity_dose2": 5
    				...
    			},
    			{
    				"session_id":"adad1",
    				...
    				"min_age_limit":18,
    				"available_capacity_dose1": 0,
    				"available_capacity_dose2": 5
    				...
    			},
    			{
    				"session_id":"adad2",
    				...
    				"min_age_limit":18,
    				"available_capacity_dose1": 5,
    				"available_capacity_dose2": 0
    				...
    			}
    		]
    	}
    	....
    	]
    }
    b
    8 replies · 2 participants
  • p

    Paul

    06/01/2021, 7:18 PM
    Introducing HiltBinder: An annotation processing library that automatically generates Dagger Hilt's @Binds methods. Just annotate your class with the @BindType annotation:
    interface ImageLoader
    
    @BindType
    class GlideImageLoader @Inject constructor(): ImageLoader
    and HiltBinder will generate the following:
    @Module
    @InstallIn(SingletonComponent.class)
    public interface HiltBinder_SingletonComponentModule {
      @Binds
      ImageLoader bind_GlideImageLoader(GlideImageLoader binding);
    }
    HiltBinder supports lots of features: • Specifying a particular type to bind to. • Installing bindings in both Dagger Hilt's predefined and custom components. • Contributing bindings into a set and map collections (Dagger multibindings). • Associating bindings with Dagger qualifiers. • KSP support. For more info, take a look at the GitHub repository that contains extensive documentation for the API as well as sample application to showcase the library in action.
    😀 1
    🤔 1
    k
    2 replies · 2 participants
  • k

    KD

    06/01/2021, 8:23 PM
    Hello, i need some help with child fragments. I’ve a bottom sheet whose content is taken care by a child fragment. Can i pass this child fragment as an param in parent bottom sheet’s constructor given i create a FragmentFactory that takes this child fragment as an argument. This approach is also limiting because i cannot pass runtime arguments to the factory, and it gets plugged in the fragmentManager once. Would be REALLY HELPFUL if there are good sample on how to deal with child fragments, esp. when system kills the process.
    :not-kotlin: 6
    r
    11 replies · 2 participants
  • s

    solidogen

    06/02/2021, 7:23 AM
    paging library: how does the library figures out if it needs to reload data on configuration change? it always shows old data for a split second, then immediately scrolls to top and does refresh+append. I’m not sure what can cause this, samples do not have this behavior - load method is not even called I can’t even debug it, debugger points me to .class files, breakpoints in kotlin equivalents don’t hit
    r
    3 replies · 2 participants
  • s

    Sergio C.

    06/02/2021, 9:55 PM
    Hi people, Does kotlin support exhaustive when without assigning a variable or without libraries?
    e
    v
    +1
    20 replies · 4 participants
  • n

    Nabeel

    06/03/2021, 6:41 AM
    Hi friends, Encountered a weird issue when using ViewBinding with Fragments. fragment_one_layout
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <include
            android:id="@+id/name"
            layout="@layout/form_element_layout" />
    
        <include
            android:id="@+id/unit"
            layout="@layout/form_element_layout" />
        <include
            android:id="@+id/quantity"
            layout="@layout/form_element_layout" />
    </LinearLayout>
    form_element_layout
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/title"
            style="@style/TextViewRegularHeading"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/title"
            android:textSize="@dimen/title_text_size" />
    
        <EditText
            android:id="@+id/input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/edit_text_forms_bg"
            android:hint="@string/form_hint"
            android:inputType="text" />
    </LinearLayout>
    After entering values in
    name.input
    ,
    unit.input
    and
    quantity.input
    fields, I've navigated to fragment_two. When returning from the fragment_two to fragment_one, the values in every field changed to the value of the
    quantity.input
    Eg : name is John, unit is Kg and quantity is 80. After navigating to fragment_two and returned, the name, unit and quantity values are changed to 80, Any help?
    :not-kotlin: 5
    j
    3 replies · 2 participants
  • s

    Slackbot

    06/03/2021, 8:41 AM
    This message was deleted.
    a
    v
    +1
    10 replies · 4 participants
  • v

    Vivek Modi

    06/03/2021, 5:54 PM
    Hey, I have a JSON response and i need to filter that data in a list. In every JSONObject there are 3 categories in which only one category holds data.
    data class CategoryResponse(
            val item: List<CategoryItem>
    )
    
    data class CategoryItem(
            val id: Int,
            val Category1: List<ItemOptions>? = null,
            val Category2: List<ItemOptions>? = null,
            val Category3: List<ItemOptions>? = null
    )
    
    data class ItemOptions(
            val name: String? = null,
            val url: String? = null
    )
    I have an enum class, which has 4 enum types
    enum class CategoryType(val name :String){
      ALL("ALL"),
      Category1("Category1"),
      Category2("Category2"),
      Category3("Category3");
    }
    There is a category named ALL, so i need the list of all the data but I don't want any null values, and still want the data that other categories hold. Example - the list consist of 5 elements  Desired output: ALL : list-> [id : 1 , category1 : ”..”] , [id : 2 ,category2 : “..”] , [id : 3 ,category2 : ”..”] , [id : 4 ,category1 : “..”] , [id : 5 ,category3: “.."]    CATEGORY2: list -> [id : 2 , category2 : “..”] , [id : 3 , category2 : “..”] (this list may or may not consist of more than 5 elements) is there any way that this list won’t occupy a lot of memory, or duplicate the objects and could be more efficient.?
    j
    8 replies · 2 participants
  • s

    Shivam Verma

    06/03/2021, 7:41 PM
    Hi guys, I have two suspend methods that I launch concurrently inside a ViewModel:
    init {
        viewModelScope.launch {
            launch { loadTotalCirculation() }
            launch { loadMarketPrice() }
        }
    }
    
    private suspend fun loadTotalCirculation() {
        val totalCirculation = bitcoinChartsRepository.getTotalCirculation(5, TimeUnit.HOURS)
        _viewState.value = _viewState.value.copy(totalCirculation = chartViewEntityMapper(totalCirculation))
    }
    
    private suspend fun loadMarketPrice() {
        val marketPrice = bitcoinChartsRepository.getMarketPrice(27, TimeUnit.DAYS)
        _viewState.value = _viewState.value.copy(marketPrice = chartViewEntityMapper(marketPrice))
    }
    However, I would like to prevent the concurrent execution of the
    _viewState.value = _viewState.value.copy...
    parts in both my methods. What's the best way to achieve this ? These two requests update parts of a stateflow that's collected inside a Fragment. However, often they run concurrently emitting the wrong states. Is there a way to better architect this solution ?
    j
    4 replies · 2 participants
  • t

    taponidhi

    06/04/2021, 5:01 AM
    How do I start multiple apps in one android project? I also want to share code between the apps. Any tutorial or official documentation which may help me with this. Thanks.
    :not-kotlin: 2
    i
    k
    4 replies · 3 participants
  • z

    Zan Skamljic

    06/04/2021, 6:39 AM
    What is the proper Kotlin Flow alternative to SingleLiveEvent?
    e
    j
    +1
    16 replies · 4 participants
  • s

    Slackbot

    06/04/2021, 10:10 AM
    This message was deleted.
    :not-kotlin: 4
    g
    1 reply · 2 participants
  • s

    Slackbot

    06/04/2021, 12:50 PM
    This message was deleted.
    g
    1 reply · 2 participants
  • z

    Zun

    06/04/2021, 12:51 PM
    I am using Dropbox Store4 (which is something like a NetworkBoundResource). I am experiencing an issue where my Fetcher is never called because my reader returns a non-null empty list (Store sees this as valid data). How can I adjust my Room DAO to return null if there are no results (so I can successfully trigger Fetch to actually load new data?). See thread for screenshots
    a
    15 replies · 2 participants
  • m

    Mărcuţ Andrei

    06/04/2021, 1:17 PM
    Hi all 👋! Does Kotlin 1.5.10 on Android 23 depend on Java 8 APIs at a lower level? I am stitching together an experimental Android/100% Kotlin project playground with the Android/Kotlin and JetPack stack without the technical legacy and I have stumbled upon this question. Is it mandatory to include Java 8 desugaring in a pure Kotlin Android project targeting minSdkLevel 23? The full Java 8 support was only added in Android 24, but I don’t plan to use the “new” Java 8 APIs. Thanks!
    e
    3 replies · 2 participants
  • m

    Muhammad Zaryab Rafique

    06/06/2021, 6:40 AM
    Hi Everyone, guide me, I want to add chat head feature in my app using kotlin lang. Give your suggestion or any documentation about it.
    :not-kotlin: 5
    z
    c
    3 replies · 3 participants
  • s

    Sudhir Singh Khanger

    06/07/2021, 4:10 AM
    Do you often use something like following to execute your code concurrently instead of synchronously? I see a lot of tasks during clean up don't need to happen synchronously.
    viewModelScope.launch {
        launch { task1 }
        launch { task2 }
    }
    g
    2 replies · 2 participants
Powered by Linen
Title
s

Sudhir Singh Khanger

06/07/2021, 4:10 AM
Do you often use something like following to execute your code concurrently instead of synchronously? I see a lot of tasks during clean up don't need to happen synchronously.
viewModelScope.launch {
    launch { task1 }
    launch { task2 }
}
g

gildor

06/07/2021, 4:45 AM
We do use it if we need parallel execution of tasks
s

Sudhir Singh Khanger

06/07/2021, 5:06 AM
Thanks
View count: 11