Hi guys, why a coroutine can return different valu...
# android
e
Hi guys, why a coroutine can return different values on each calls ? I am testing a function which makes use of coroutines and google geocoder and I am mocking the geocode method to return the value that I want to return but sometimes it returns empty string making my test fails. My code is
Copy code
@JvmStatic
    @BindingAdapter(value = ["app:geocodeLocation","app:geocode"],requireAll = true)
    fun setAddress(view: TextView, state : MutableListViewState<Data>, geocoder : Geocoder) {

        launch(UI) {

            val text = state.first()?.carPosition?.let {
                async(geocoder,it.latitude, it.longitude)
            } ?: view.context.getString(R.string.bottom_sheet_no_address)

            view.animateText(text)
        }
    }

    suspend fun async(geocoder: Geocoder , latitude : Double, longitude : Double) : String? {
        return async(CommonPool) { getAddress(geocoder,latitude,longitude) }.await()
    }

    private fun getAddress(geocoder: Geocoder , latitude : Double, longitude : Double) : String? {
        val addresses = geocoder.getFromLocation(latitude, longitude, 1)
        print(addresses)
        return addresses.takeIf { it.isNotEmpty() }?.let { it.first().thoroughfare }

    }
Test code
Copy code
@Test
    fun `set address should return correct address when there are good coordinates`() {
        val car = CarPosition(1,2,42.3,-3.4,12.2f,10f,"","")
        val data = Data(1,2,14, car, listOf() )
        `when`(geocoder.getFromLocation(42.3,-3.4,1)).thenReturn(listOf(FakeAddress("Address")))

        val state = MutableListViewState<Data>()
        state.data(listOf(data))

        val view = TextView(context)

        runBlocking { Bindings.setAddress(view, state, geocoder) }

        view.text shouldEqual "Address"

    }

    private class FakeAddress(dir : String) : Address(Locale.getDefault()){
        init {
            thoroughfare = dir
        }
    }
I am using @get:Rule
Copy code
var rule = InstantTaskExecutorRule()
to test live data postValue that is executed on my state.data