Skip to content

Instantly share code, notes, and snippets.

@0phelia
Created February 26, 2021 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0phelia/e72d7113f0b3118b90e2163ec5769928 to your computer and use it in GitHub Desktop.
Save 0phelia/e72d7113f0b3118b90e2163ec5769928 to your computer and use it in GitHub Desktop.
package de.stroeer.androiddevapplicant
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class WeatherViewModel : ViewModel() {
// repos
val repository1 = WeatherTempForecastRepository()
val repository2 = WeatherPrecipitationForecastRepository()
val repository3 = GeocodingRepository()
// observable properties for forecast
private val _combinedForecast = MutableLiveData<Pair<TemperatureForecast, PrecipitationForecast>>()
val combinedForecast: LiveData<Pair<TemperatureForecast, PrecipitationForecast>>
get() = _combinedForecast
var loading = MutableLiveData<Boolean>(false)
var error = MutableLiveData<Exception?>(null)
// observable properties for location suggestions
var locationSearchSuggestions = MutableLiveData<List<LocationSuggestion>>()
fun fetchForecastForLocation(ls: LocationSuggestion) {
GlobalScope.launch(Dispatchers.IO) {
loading.postValue(true)
try {
val forecast1 = repository1.fetchTempForecast(ls).await()
val forecast2 = repository2.fetchPrecipForecast(ls).await()
_combinedForecast.postValue(Pair(forecast1, forecast2))
loading.postValue(false)
} catch (e: Exception) {
error.postValue(e)
}
}
}
fun fetchLocationSuggestions(userInput: String) {
GlobalScope.launch(Dispatchers.IO) {
val suggestionResponse = repository3.getSuggestions(userInput).await()
// only first 5 suggestions should be shown
val suggestions = mutableListOf<LocationSuggestion>()
for (i in 0..suggestionResponse.suggestions.size - 1) {
if (i < 5) {
suggestions.add( suggestionResponse.suggestions[i] );
}
}
locationSearchSuggestions.postValue(suggestions)
}
}
}
data class TemperatureForecast(
val temperatureInCelsius: Double? = null
)
data class PrecipitationForecast(
val precipitationProbabilityInPercent: Int? = null
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment