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

    Olenyov Kirill

    03/05/2020, 9:46 PM
    Hi, does anybody know about some equivalent for hasSubscribers() method in ConflatedBroadcastChannel? I want to implement Repository pattern with updateIfNeeded() method and I need to know if there are real subscribers(views) to my repo..
    z
    • 2
    • 3
  • s

    Slackbot

    03/05/2020, 11:37 PM
    This message was deleted.
    m
    • 2
    • 1
  • g

    gabin

    03/06/2020, 10:16 AM
    Hi guys. What is the difference between liveData {} and viewModelScope {} builders in ViewModel? Does liveData survive activity recreation?
    s
    a
    • 3
    • 5
  • k

    Kirill Prybylsky

    03/06/2020, 12:44 PM
    Hi! Is it okay to check via ConnectivityManager do user have an internet connection?
    :google: 1
    :yes: 4
    :stackoverflow: 1
    🇳🇴 2
    o
    j
    • 3
    • 15
  • o

    Orhan Tozan

    03/06/2020, 10:41 PM
    Hey guys, I'm trying to migrate all of our Android build.gradle files to build.gradle.kts. I'm having a hard time finding the right syntaxes and names, all Android documentation only gives Groovy examples. Is there some documentation where I can find all DSL methods etc.?
    t
    v
    • 3
    • 3
  • s

    Slackbot

    03/07/2020, 12:14 AM
    This message was deleted.
    d
    k
    • 3
    • 3
  • j

    Joshua

    03/07/2020, 9:20 PM
    :stackoverflow: 1
    :google: 1
    t
    • 2
    • 3
  • a

    Abed Murad

    03/08/2020, 11:50 AM
    Hi, Can someone please tell me what does
    out
    mean in this context ? , thanks.
    /**
     * A generic class that holds a value with its loading status.
     * @param <T>
     */
    sealed class Result<out R> {
    
        data class Success<out T>(val data: T) : Result<T>()
        data class Error(val exception: Exception) : Result<Nothing>()
        object Loading : Result<Nothing>()
    
        override fun toString(): String {
            return when (this) {
                is Success<*> -> "Success[data=$data]"
                is Error -> "Error[exception=$exception]"
                Loading -> "Loading"
            }
        }
    }
    
    /**
     * `true` if [Result] is of type [Success] & holds non-null [Success.data].
     */
    val Result<*>.succeeded get() = this is Success && data != null
    m
    • 2
    • 1
  • b

    bhatnagarm

    03/08/2020, 1:20 PM
    Hey guys, did anyone try writing Repository class with suspend function where the data is wrapped into NetworkBoundResource(showcased in architecture component sample GithubBrowser) and then exposed to ViewModel.
    s
    g
    +3
    • 6
    • 18
  • k

    Kulwinder Singh

    03/09/2020, 7:58 AM
    How can we mock
    FirebaseAuth.getInstance().signInWithCustomToken(token).addOnCompleteListener{}
    and other Task like
    addOnSuccessListener
    and
    addOnFailureListener
    using MockK ?
    s
    m
    l
    • 4
    • 25
  • j

    jossiwolf

    03/09/2020, 11:10 AM
    I'm trying to parcelize an inline class but I'm getting a runtime crash
    java.lang.NoClassDefFoundError: Failed resolution of: LpackaageName/DealershipId$Creator;
    @Parcelize
    inline class DealershipId(val value: String): Parcelable
    Did anybody encounter this? Kotlin 1.3.70, but wasn't working on 1.3.61 either
    l
    • 2
    • 6
  • l

    louiscad

    03/09/2020, 11:47 AM
    Hi, did anyone there made their
    NotificationCompat
    Kotlin extensions? I personally made some, and I'm looking for folks to discuss API design regarding extensions for these APIs. I'm looking forward exchanging inspiration to get to a DSL that is the lest error-prone and forget-prone possible, and very readable (can't stand these
    NotificationCompat.PRIORITY_
    and similar prefixes). Right, this is what I have, and I know I can make improvements, but I'd like to bounce off improvement ideas.
    val notification = buildNotification(ChannelIds.Something) {
        priority = NotificationCompat.PRIORITY_MAX
        category = NotificationCompat.CATEGORY_STATUS
        visibility = Public
        contentText = "Some content text"
        smallIcon = R.drawable.ic_some_icon_white_24dp
    }
    d
    • 2
    • 7
  • m

    Mickael

    03/09/2020, 2:48 PM
    //Compare 2 json files
    val parser = JsonParser()
    val o1 = parser.parse("{\"state\":1,\"cmd\":1}")
    val o2 = parser.parse("{\"state\":1,\"cmd\":1}")
    
    println(o1 == o2)
    This seems to be enough ;-)
    l
    • 2
    • 1
  • e

    Ellen Spertus

    03/09/2020, 6:48 PM
    I’m trying to understand how companion objects lifetimes interact with the Android lifecycle. I have an app that includes something like this:
    class MainActivity {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            Metadata.initialize()
        }
    }
    
    class Metadata {
        companion object {
            boolean initialized = false
    
            fun initialize(context: Context) {
                check(!initialized)
                // do stuff (omitted)
                initialized = true
            }
        }
    }
    Sometimes my app fails because the
    check
    at the beginning of
    Metadata.initalize()
    fails, which implies that the companion object is surviving the destruction of
    MainActivity
    , despite their presumably being in the same process. Could someone help me understand why the companion object stays around even if the activity needs to be re-created?
    c
    z
    c
    • 4
    • 11
  • a

    Arseniy

    03/10/2020, 12:09 AM
    Hey, does anyone know a good open source photo editor?
    :google: 4
    s
    s
    +2
    • 5
    • 7
  • n

    Nikola Milovic

    03/10/2020, 8:27 AM
    Any reason my layout is not being found? this is R
    com.nikolam.nsdkelper public final class com.nikolam.nsdkelper.R
    and this is what's happening, the last thing i added was my library module to my app.gradle
    dependancies{
    implementation project(":nsdkelper")
    }
    I tried the solutions found online, the cache, the rebuild and so on, but haven't had any luck.
    s
    • 2
    • 3
  • k

    Kulwinder Singh

    03/10/2020, 12:11 PM
    for MockK, i'm getting
    MockKException: no answer found for: MyClass(#1).sendMessage(okhttp3.RequestBody$2@4ed4bd33)
    , actually RequestBody's properties are same just instance is different. that's why it did not matches parameters but if i add
    any()
    instead of requestbody it works. is there anything else i can use instead of
    any()
    here ?
    every {	myClass.sendMessage(MockRequest.createTestBody(value="text")) } answers { something }
    
    ....
    
    class SomeObject(myClass:MyClass){
    	fun doSomething(text: String): Flowable<Result<Boolean>> {
            val request = MockRequest.createTestBody(text)
    		myClass.sendMessage(request)
    	}
    }
    ....
    i have checked documentation of mockk but didn't found anything, that's why asked here:
    m
    • 2
    • 3
  • a

    Arslan Mushtaq

    03/10/2020, 12:51 PM
    How can I change the Toolbar font while I have structed my styles.xml like this
    styles.xml
    a
    • 2
    • 1
  • e

    Elyes

    03/10/2020, 3:17 PM
    Does anyone know why the
    onDestory
    function of a fragment wouldn’t be called when closing the app ?
    s
    k
    s
    • 4
    • 11
  • b

    basher

    03/10/2020, 4:24 PM
    does anyone know the difference between the kotlin-android and kotlin-android-extensions plugins? i see people applying both, but i can't find any official doc reference to kotlin-android anymore
    d
    j
    b
    • 4
    • 6
  • m

    Mikołaj Kąkol

    03/10/2020, 4:58 PM
    is there an easy way to have a`scope` that would cancel job in
    onStop
    . I'm thinking of equivalent of: https://github.com/trello/RxLifecycle So I would like start
    Flow
    in
    onStart
    and have it canceled by
    onStop
    . From what I see
    LifecycleCoroutineScope
    has only option to cancel it on destroy
    j
    • 2
    • 2
  • e

    Ellen Spertus

    03/10/2020, 5:27 PM
    I’d like to start using
    ViewModel
    for my state. Could anyone advise me how to adapt the https://developer.android.com/topic/libraries/architecture/viewmodel example to support the case where an argument needs to be passed into
    getUsers()
    and through to
    loadUsers()
    for it to do its job?
    class MyViewModel : ViewModel() {
        private val users: MutableLiveData<List<User>> by lazy {
            MutableLiveData().also {
                loadUsers()
            }
        }
    
        fun getUsers(): LiveData<List<User>> {
            return users
        }
    
        private fun loadUsers() {
            // Do an asynchronous operation to fetch users.
        }
    }
    I could store the information in an instance variable from
    getUsers()
    and retrieve it from
    loadUsers()
    , but that doesn’t seem very nice. What I need to pass in is a
    Context
    (to access assets and the package manager). I don’t cache the Context.
    a
    a
    a
    • 4
    • 11
  • u

    182630g

    03/11/2020, 1:42 AM
    is this channel to help with kotlin on android studio ?
    a
    m
    • 3
    • 4
  • t

    tjohnn

    03/11/2020, 12:00 PM
    Android studio gives me this error after upgrading android studio kotlin plugin version to
    1.3.70-eap-42-Studio3.6-1
    Cause: org.gradle.tooling.model.kotlin.dsl.KotlinDslScriptsModel can only be requested on the root project, got 'project ':app''
    PS: I am not using kotlin dsl for gradle, I am using groovy
    r
    • 2
    • 5
  • g

    Gavin Ray

    03/11/2020, 5:07 PM
    Kotlin as a language is comfy though, barring the Android bit.
    m
    c
    • 3
    • 75
  • d

    dekans

    03/11/2020, 5:29 PM
    Is it possible to enable assertions in Android debug builds via gradle (and not in release builds)?
    j
    • 2
    • 2
  • s

    Sergio C.

    03/11/2020, 10:07 PM
    why can’t I update to android studio 4.0 beta 2 from mac?
    t
    z
    s
    • 4
    • 7
  • g

    Guy Bieber

    03/11/2020, 11:21 PM
    I have a module that I modified and rebuilt. However when debugging an app that uses the module it appears to be using an old version of the module. I have cleaned and rebuilt everything, but nothing seems to work. Any ideas?
    w
    a
    • 3
    • 8
  • a

    Almas Shagdarov

    03/12/2020, 4:39 AM
    How to wait for ListAdapter.submitList() to execute and call RecyclerView.smoothScrollToPosition(0);
    c
    • 2
    • 1
  • o

    Ofir Bar

    03/12/2020, 8:53 AM
    Source code:
    fun getCityById(selectedCityId: Int): City {
        var city : City? = null
        viewModelScope.launch {
            city = locationRepository.getSingleCityFromDatabaseById(selectedCityId)
        }
        return city //Compilation error message: type mismatch, Required:City, found: City?
    }
    
    fun getListOfLanguagesByIds(selectedLanguages: List<Int>): List<Language> {
        viewModelScope.launch {
            return supportedLanguagesRepository.getLanguagesFromDatabaseById(selectedLanguages.toIntArray())
        }// Compilation error above message: 'return' is not allowed here
    }
    
    fun getExpertiseFieldById(expertiseFieldId: Int): ExpertiseField {
        lateinit var expertiseField : ExpertiseField
        viewModelScope.launch {
            expertiseField = expertiseFieldsRepository.getSingleExpertiseFieldFromDatabaseById(expertiseFieldId)
        }
        return expertiseField
        //Seems to work, but I am afraid expertiseField will be returned uninitialized.
    }
    r
    • 2
    • 1
Powered by Linen
Title
o

Ofir Bar

03/12/2020, 8:53 AM
Source code:
fun getCityById(selectedCityId: Int): City {
    var city : City? = null
    viewModelScope.launch {
        city = locationRepository.getSingleCityFromDatabaseById(selectedCityId)
    }
    return city //Compilation error message: type mismatch, Required:City, found: City?
}

fun getListOfLanguagesByIds(selectedLanguages: List<Int>): List<Language> {
    viewModelScope.launch {
        return supportedLanguagesRepository.getLanguagesFromDatabaseById(selectedLanguages.toIntArray())
    }// Compilation error above message: 'return' is not allowed here
}

fun getExpertiseFieldById(expertiseFieldId: Int): ExpertiseField {
    lateinit var expertiseField : ExpertiseField
    viewModelScope.launch {
        expertiseField = expertiseFieldsRepository.getSingleExpertiseFieldFromDatabaseById(expertiseFieldId)
    }
    return expertiseField
    //Seems to work, but I am afraid expertiseField will be returned uninitialized.
}
r

Raul Tunduc

03/13/2020, 7:11 AM
why you do not use LiveData?
View count: 2