在观察员内部的协程内部进行地理编码未运行

时间:2020-04-19 19:03:42

标签: android-studio kotlin geocoding kotlin-coroutines

在我的片段中,我有一个bindUI()方法,该方法包含一些正在观察的liveData,并且在lambda内部,我想使用值location(包含一个纬度和经度值)来检索基于其包含的坐标的地址列表。有人告诉我,地理编码应该在协程内部完成,因此我正在尝试这样做,但是launch协程内部的代码似乎没有运行。我已经放置了日志语句,但是它们没有运行,并且似乎没有结果打印在我的textView上。调试器还说,当我在其上放置断点时,没有可运行的代码。我在这弄什么?

private fun bindUI() = launch(Dispatchers.Main) {
        // fetch the location
        val weatherLocation = viewModel.weatherLocation.await()

        // Observe the location for changes
        weatherLocation.observe(viewLifecycleOwner, Observer { location ->
            if (location == null) return@Observer
            //TODO:sp update the location text view
            launch(Dispatchers.Main) {
                val task = updateLocation(location)
                locationTxtView.text = task[0].countryName
            }
        })
    }

这是updateLocation()的乐趣:

private suspend fun updateLocation(location: WeatherLocation): MutableList<Address> {
    return async(Dispatchers.IO) {
        val geocoder = Geocoder(activity, Locale.getDefault())
        val addr = geocoder.getFromLocation(location.latitude, location.longitude, 10)
        return@async addr
    }.await()
}

0 个答案:

没有答案