我制作了一个基于MVVM架构的天气应用程序,其中我使用GPS来获取设备位置,并将该位置传递给天气API服务以获取“天气报告”,但是由于该位置可能会改变并且用户需要再次获取新位置的天气,我将该位置包装在LiveData中并进行观察,并将其传递给API服务类。
简而言之,我将在LiveData的observeForever内部使用GlobalScope启动一个协程
WeatherNetworkAbstractionsImpl.kt
class WeatherNetworkAbstractionsImpl(
private val weatherApiService: WeatherApiService,
private val context: Context
) : WeatherNetworkAbstractions {
private val _downloadedWeather = MutableLiveData<WeatherResponse>()
override val downloadedWeather: LiveData<WeatherResponse>
get() = _downloadedWeather
override suspend fun fetchWeather(location: LiveData<String>) {
try {
location.observeForever {
GlobalScope.launch(Dispatchers.IO) {
val fetchedWeather = weatherApiService.getWeather(it).await()
_downloadedWeather.postValue(fetchedWeather)
}
}
}
catch (e: NoConnectivityException){
Log.e("Connectivity","No internet connection.",e)
}
}
}
Repository.kt
class RepositoryImpl(
private val weatherDao: WeatherDataDao,
private val weatherNetworkAbstractions: WeatherNetworkAbstractions,
private val weatherLocationDao: WeatherLocationDao,
private val recordMapperImpl: RecordMapperImpl,
private val locationMapperImpl: LocationMapperImpl,
private val locationProvider: LocationProvider
) : Repository {
init {
weatherNetworkAbstractions.downloadedWeather.observeForever {latestWeatherReports->
persistLatestWeatherReports(latestWeatherReports, recordMapperImpl, locationMapperImpl)
}
}
}
我收到此错误:
无法在后台线程上调用observeForever
即使我将Dispatchers.IO更改为Dispatchers.Main,但仍然遇到相同的错误。
如何解决此问题?我是协程新手。