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

    suhas

    08/24/2021, 8:13 AM
    #NotKotlin Which slack workspace is popular for android related queries? Android Chat or Android United?
    p
    • 2
    • 2
  • t

    Tower Guidev2

    08/24/2021, 11:22 AM
    Hi, Im trying out
    Apollo3
    for my Android GraphQL client calls
    m
    • 2
    • 16
  • t

    The Monster

    08/24/2021, 11:01 PM
    binding.button.setOnClickListener( View.OnClickListener {
    
    })
    
    binding.button.setOnClickListener {
    
    }
    Hey guys I am confused why I was able to skip the parenthesis on the 2nd example. The method takes a functional interface, but not a function, so how am I allowed to use the passing trailing lambda syntax here?
    ✅ 1
    a
    • 2
    • 1
  • n

    nilTheDev

    08/25/2021, 6:52 AM
    I have a
    LiveData
    of type
    MutableLiveData<MutableList<User>>
    . I have an issue. If I update the
    value
    by another
    MutableList<User>
    the changes are emitted to the observers. However, if I simply add other elements to the
    MutableList<User>
    , that is already initialised in the
    LiveData
    , the changes are not emitted. Here is what I am doing...
    //other codes 
    private val _users: MutableLiveData<MutableList<User>> = MutableLiveData<MutableList<User>>()
    
    init {
        _users.value = mutableListOf<User>()
    }
    
    val uiScope = CoroutineScope(Dispatchers.Main + Job())
    
    fun loadUsers(){
        uiScope.launch{
            // this works perfectly
            _users.value = fetchUsers() as MutableList<User>
            // this doesn't work... no idea why
            _users.value.addAll(fetchUsers())
        }
    }
    
    suspend fun fetchUsers(): List<User>{
        return withContext(<http://Dispatchers.IO|Dispatchers.IO>){
            //fetch users asynchronously
        }
    }
    This is just an emulation of the actual program. That actual code is not that trivial.
    d
    a
    a
    • 4
    • 8
  • n

    Nikolay Puliaev

    08/25/2021, 8:59 AM
    Hi. Is it possible to use some kotlin-based bridges to C++ instead of JNI?
    g
    • 2
    • 3
  • h

    haris mehmood

    08/25/2021, 11:09 AM
    "data": [
        {
          "player_id": 2497,
          "firstname": "Jay-Alistaire Frederick",
          "lastname": "Simpson",
          "birthday": "1988-12-01",
          "age": 32,
          "weight": 85,
          "height": 180,
        },
        {
          "player_id": 2570,
          "firstname": "Simranjit",
          "lastname": "Singh Thandi",
          "birthday": "1999-10-11",
          "age": 21,
          "weight": null,
          "height": null,
        }]
    Hi i want to replace value of "weight" to 0 if its null from backend. How to do it in Data Class ? Any solution
    o
    n
    • 3
    • 5
  • t

    Travis Griggs

    08/25/2021, 8:26 PM
    I was trying to be clever with compareTo: override:
    override fun compareTo(other: ValveSpan): Int {
        val fields = listOf(ValveSpan::begin, ValveSpan::end, ValveSpan::userTitle)
        val comparisons = fields.asSequence().map { field -> field(this).compareTo(field(other)) }
        return comparisons.firstOrNull { n -> n != 0 } ?: 0
    }
    Basically an arbitrary number of accessors, work through them lazily until i get to a non zero return and return that. But the compiler complains because:
    Type mismatch.
    Required: {Duration & String}
    Found: {Comparable{Duration & String}> & Serializable}
    my begin and end accessors do indeed return Durations and the userTitle does indeed return a String. I'm not entirely clear on what the compiler is not happy about here though. it seems like its figuring it out kind of, but not all the way. or there's some stupid syntax error that will only finally embarssingly occur to me finally after pressing send...
    e
    c
    • 3
    • 3
  • t

    Travis Griggs

    08/25/2021, 10:57 PM
    what's the idiomatic way to create a Set (immutable) from a collection mapping operation? The following works, but seems kind of round about:
    val beginEdges: Set<Duration>
        get() = emptySet<Duration>() + spans.asSequence().map({ span -> span.begin })
    setOf() takes varargs, but I'm not aware of a pythonesque ability to ** an iterable argument to varargs...
    e
    • 2
    • 4
  • c

    Caio Costa

    08/26/2021, 3:53 AM
    Hello folks. Is there a way to avoid MutableStateFlows posting the same value when the screen is rotated like what we have with SingleLiveEvent version of LiveData? I'm using this guy right here:
    private val _errorStateFlow = MutableStateFlow<State<Error>>(InitialError)
        internal val errorStateFlow: StateFlow<State<Error>>
            get() = _errorStateFlow
    Since it is an Error StateFlow, everytime it posts something, i show a SnackBar on the screen but i just want to do this one time for each time the error occurs. Any thoughts on it? Appreciate ya 👍
    a
    s
    +3
    • 6
    • 6
  • m

    Matthew Laser

    08/26/2021, 2:33 PM
    has the
    Duration
    API always been experimental? I swear I used it years ago and it wasn't. Am I making this up? 😛
    d
    c
    • 3
    • 3
  • m

    maxmello

    08/26/2021, 3:14 PM
    I’m currently still using lots and lots of LiveData in my project. In fact, I just added even more LiveData. Now, I have skipped frames on some devices (which are older devices with older OS versions) during testing. I’m not 100% certain it is because of the LiveData, or if I accidentally introduces a bug along the way. In either case, could I assume a performance improvement when switching to Kotlin Flows? I know LiveData does still a lot on the main thread under the hood, so I would assume the main thread can be freed from computations by switching to Flow?
    l
    • 2
    • 2
  • j

    Jason Inbody

    08/26/2021, 5:15 PM
    I orginally wrote an app in crossplatform framework (mistakes were made) and I've converted it to a kotlin jetpack compose app. Well... the main activity file structure was
    org.kivy.android.PythonActivty
    . Do I have to keep that naming convention for my main activity when I upload to google play? Or can that be changed between versions?
    e
    • 2
    • 2
  • a

    Andy Gibel

    08/26/2021, 7:52 PM
    I have what I feel may be silly questions but I can't find a good reference anywhere. I'm making an SDK to be used by Android. In the SDK I'm exposing server endpoints and also doing some behind the scenes UDP broadcast listening. The SDK will be consumed by Java but written in Kotlin. Few questions: 1. In general, should libraries and SDKs be doing behind-the-scenes threading? For instance, I'd like my SDK to start listening for UDP events on a background thread on init. Should the multi-threading be handled explitcitly be the client of the code? 2. If I were to do multiple threads behind the scenes, Is there any way to run code in a coroutine/thread and then have the results post to the main thread without coupling the SDK with Android (requiring context)? 3. If an SDK were to offer an asynchronous API using callbacks for Java consumption and Flow for Kotlin, what is a clean way to dynamically include bindings for one or the other based on dependencies pulled in? (e.g. `implementation("mySDK-core") and implementation("mySDK-ktx")? Any docs or references on SDK or library design in general would be greatly apprecaited. Thanks in advance!
    d
    • 2
    • 3
  • t

    Travis Griggs

    08/26/2021, 9:03 PM
    A couple years ago when I first starting learning Kotlin, porting an iOS Swift app, there wasn't a real comparable idiom to the Swift Enums which can capture values. I'm curious what the general approach now days for expressing something like the following Swift idiom in Kotlin?
    enum ValveRunInterval {
        case future(start:Date, plan:Plan)
        case active(interval:DateInterval, plan:Plan)
        ...
    }
    I could use a little abstract/two subclass triad to express this. Not sure what the rules are when combining data classes and inheritance. Is there a better/different way?
    d
    m
    • 3
    • 2
  • s

    Slackbot

    08/27/2021, 7:28 AM
    This message was deleted.
    :not-kotlin: 4
    l
    • 2
    • 1
  • h

    Hovhannes

    08/27/2021, 12:52 PM
    Hello, is it ok to pass data from Repositories to RemoteDataSource in MVVM?
    :not-kotlin: 1
    h
    o
    • 3
    • 2
  • w

    William Reed

    08/27/2021, 1:52 PM
    hi all - i have a bundle provided during a notification payload. i want to convert this into a
    data class
    that the bundle is expected to conform to. is there any out of the box way to do this? i’m sure it could be done with a code gen library, just not sure if it’s been done before
    e
    • 2
    • 2
  • s

    Slackbot

    08/27/2021, 9:21 PM
    This message was deleted.
    :stackoverflow: 1
    :not-kotlin: 1
    l
    e
    • 3
    • 2
  • h

    hfhbd

    08/28/2021, 7:56 PM
    Why is
    ViewModelProvider.Factory
    not a
    fun interface
    ? This would allow you to pass a lambda instead.
    e
    • 2
    • 7
  • l

    Lilly

    08/28/2021, 10:02 PM
    Disclaimer: Not 100% Kotlin related I was looking at the
    Bluetooth permissions
    docs and there is stated:
    <manifest ... >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <!-- If your app targets Android 9 or lower, you can declare
         ACCESS_COARSE_LOCATION instead. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...
    </manifest>
    I'm wondering: When I follow this advice I end up declaring both permission FINE and COARSE, while I can restrict the use of COARSE:
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"
            android:maxSdkVersion="28" />
    But can I configure FINE_LOCATION so that it's only declared when API is >28? I mean isn't it a problem when I have both permission declared although I only need one of them at the same time? Same goes for the new permission BLUETOOTH_CONNECT/SCAN that is only needed on API level 31. I'm also wondering why FINE_LOCATION is stucked out on the New Bluetooth permissions in Android 12 page. Isn't it better to declare FINE_LOCATION like the other
    legacy
    permissions:
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
        android:maxSdkVersion="30" />
    This permission is still needed on API level 29 or lower.
    :not-kotlin: 4
    l
    • 2
    • 2
  • s

    Slackbot

    08/30/2021, 3:59 AM
    This message was deleted.
    :not-kotlin: 3
    :thread-please: 6
    😒 1
    l
    • 2
    • 3
  • j

    Johnjake Talledo

    08/30/2021, 5:31 AM
    Hi how do I make the java folder a root directory? when I created a module
    base-persistence
    only
    unit test folder
    and
    ui test
    are the defaults so I created a root folder or directory but everytime I create a sub folder it creates another new directory. Eg: In
    com.metromart.runner_persistence
    I want to create a sub directory called base but instead it creates another folder,
    com.metromart.runner_persistence.base
    .
    l
    • 2
    • 3
  • s

    Slackbot

    08/30/2021, 8:40 AM
    This message was deleted.
    :not-kotlin: 6
    l
    m
    • 3
    • 4
  • v

    Vivek Modi

    08/30/2021, 5:01 PM
    Why is it important to clear the 
    binding
     in 
    onDestroyView
     when implementing Android View Binding in a Fragment?
    :not-kotlin: 4
    n
    u
    +3
    • 6
    • 15
  • k

    Klaas Kabini

    08/30/2021, 6:39 PM
    Hi, I have an issue in my unit tests where the LiveData does not dispatch the value to the observer registered using
    LiveData.observeForever
    . Does anyone has an idea as to what might be causing that?
    a
    m
    • 3
    • 3
  • с

    Стоян Тинчев

    08/30/2021, 6:39 PM
    Hi, I want to build an app with which you can create events like google calendar but only for the current day. I imagine a vision like when you select one day view in google calendar. Also probably need the dynamic size of the events because they must look different when are for 5 minutes and when for 1 hour. Generally, an experience like google calendar. What is the best solution in your opinion - recyclerView or there is something better?
    :kotlin-intensifies: 1
    :not-kotlin: 2
    o
    j
    • 3
    • 2
  • j

    Jacob

    08/31/2021, 3:58 AM
    Never use vars in a data class. Only val. With immutable objects a shallow copy is equivalent to a deep copy!
    ☝️ 3
    i
    a
    s
    • 4
    • 3
  • p

    partap

    08/31/2021, 2:20 PM
    @everyone please help me. I have this error that path doesn't exist actually. Have a look and guide me.
    :not-kotlin: 4
    n
    • 2
    • 1
  • d

    David Alford

    08/31/2021, 4:42 PM
    Hello, I'm working on launching my app from a URL. I have the intent-filter set up in my manifest:
    <activity
    			android:name=".MyTargetActivity"
    			android:screenOrientation="portrait">
    
    			<intent-filter android:autoVerify="true">
    				<action android:name="android.intent.action.VIEW" />
    
    				<category android:name="android.intent.category.DEFAULT" />
    				<category android:name="android.intent.category.BROWSABLE" />
    
    				<data
    					android:host="my.host.com"
    					android:scheme="https" />
    				<data
    					android:host="my.host.com"
    					android:scheme="http" />
    			</intent-filter>
    		</activity>
    I've created the intent from the URL:
    val url: HttpUrl = HttpUrl.Builder()
    			.scheme("https")
    			.host("<http://my.host.com|my.host.com>")
    			.addPathSegment("invite")
    			.addQueryParameter("voucher", voucherContents)
    			.build()
    		val sendIntent: Intent = Intent().apply {
    			action = Intent.ACTION_SEND
    			putExtra(Intent.EXTRA_TEXT, url.toString())
    			type = "text/plain"
    			toUri(0)
    		}
    		val shareIntent = Intent.createChooser(sendIntent, url.host)
    		startActivity(context, shareIntent, null)
    This pops up a chooser window where I can select an app or copy to clipboard. I choose the latter and then open up an app such as Slack or Sheets or something and paste it in. When I click the URL link I just pasted, it opens MyTargetActivity successfully, but it's in the app that opened it rather than a new application. How do I get it to launch as a standalone application? (I've also written the server part and gotten that working. I can rummage that up if needed.)
    :not-kotlin: 4
    u
    d
    • 3
    • 7
  • m

    Milan Vadhel

    09/01/2021, 5:48 AM
    Hello I am implementing one sample for unit testing. This is my test class.
    @SmallTest
    @RunWith(MockitoJUnitRunner::class)
    @ExperimentalCoroutinesApi
    class CharacterViewModelTest {
    
    
        @get:Rule
        val instantTaskExecutorRule = InstantTaskExecutorRule()
    
        @get:Rule
        val testCoroutineRule = TestCoroutineRule()
    
        @Mock
        lateinit var characterUseCase: CharacterUsecase
    
        @Mock
        lateinit var characterRepository: CharacterRepository
    
        @Mock
        lateinit var characterLiveData: Observer<UiState<ArrayList<CharacterItem>>>
    
        private val characterViewModel: CharacterViewModel by lazy {
            CharacterViewModel(characterUseCase)
        }
    
        @Test
        fun test_characterApiCallSuccess() {
            stubCharacterApiSuccess()
            characterViewModel.charactersLiveEvent.observeForever(characterLiveData)
            characterViewModel.getCharacters(1)
            verify(characterLiveData).onChanged(UiState.Loading()) // Test Loading Response
            verify(
                characterLiveData
            ).onChanged(UiState.Success(characterApiResponse())) // Test Success Response
            characterViewModel.charactersLiveEvent.removeObserver(characterLiveData)
        }
    
        private fun stubCharacterApiSuccess() {
            testCoroutineRule.runBlockingTest {
                doReturn(characterApiResponse())
                    .`when`(characterRepository)
                    .getCharacters(1)
            }
        }
    }
    I am getting below error..
    Wanted but not invoked:
    characterLiveData.onChanged(
    Success(data=[CharacterItem(name=Rick Sanchez, image=<https://rickandmortyapi.com/api/character/avatar/1.jpeg>, status=Alive, gender=Male, species=Human)])
    );
    -> at com.example.databindingsample.CharacterViewModelTest.test_characterApiCallSuccess(CharacterViewModelTest.kt:55)
    Actually, there were zero interactions with this mock.
    I can't figure out what this error is saying. Is there any thing i am doing wrong. Any one have any idea about it?
    k
    • 2
    • 2
Powered by Linen
Title
m

Milan Vadhel

09/01/2021, 5:48 AM
Hello I am implementing one sample for unit testing. This is my test class.
@SmallTest
@RunWith(MockitoJUnitRunner::class)
@ExperimentalCoroutinesApi
class CharacterViewModelTest {


    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    val testCoroutineRule = TestCoroutineRule()

    @Mock
    lateinit var characterUseCase: CharacterUsecase

    @Mock
    lateinit var characterRepository: CharacterRepository

    @Mock
    lateinit var characterLiveData: Observer<UiState<ArrayList<CharacterItem>>>

    private val characterViewModel: CharacterViewModel by lazy {
        CharacterViewModel(characterUseCase)
    }

    @Test
    fun test_characterApiCallSuccess() {
        stubCharacterApiSuccess()
        characterViewModel.charactersLiveEvent.observeForever(characterLiveData)
        characterViewModel.getCharacters(1)
        verify(characterLiveData).onChanged(UiState.Loading()) // Test Loading Response
        verify(
            characterLiveData
        ).onChanged(UiState.Success(characterApiResponse())) // Test Success Response
        characterViewModel.charactersLiveEvent.removeObserver(characterLiveData)
    }

    private fun stubCharacterApiSuccess() {
        testCoroutineRule.runBlockingTest {
            doReturn(characterApiResponse())
                .`when`(characterRepository)
                .getCharacters(1)
        }
    }
}
I am getting below error..
Wanted but not invoked:
characterLiveData.onChanged(
Success(data=[CharacterItem(name=Rick Sanchez, image=<https://rickandmortyapi.com/api/character/avatar/1.jpeg>, status=Alive, gender=Male, species=Human)])
);
-> at com.example.databindingsample.CharacterViewModelTest.test_characterApiCallSuccess(CharacterViewModelTest.kt:55)
Actually, there were zero interactions with this mock.
I can't figure out what this error is saying. Is there any thing i am doing wrong. Any one have any idea about it?
k

Klaas Kabini

09/01/2021, 6:21 AM
Your unit test is incorrect. You have to verify the behaviour of the collaborator which is the CharacterUseCase not the observer. The observer is not the collaborator. The CharacterUseCase is the interactor(or collaborator) that is used by the view model to achieve a specific use case.
I also noticed that when observing using non-lifecycle bound observers the onChanged does not get called at times and behaves strangely. I had to do this to get it to catch the onChanged events.
fun <T> LiveData<T>.attachDisposableObserver(time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS, afterObserve: ()-> Unit) {
   
    val latch = CountDownLatch(1)

    val observer = object : Observer<T> {
        override fun onChanged(t: T?) {
            
            latch.countDown()
            this@gattachDisposableObserver.removeObserver(this)
        }
    }

    this.observeForever(observer)

    try{
    
       // Don't wait indefinitely if the LiveData is not set.
      if (!latch.await(time, timeUnit)) {
        throw TimeoutException("LiveData value was never set.")
      }
    } finally{
        this.removeObserver(observer)
    }

    afterObserve.invoke()
}
View count: 13