diff --git a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherAppViewModel.kt b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherAppViewModel.kt index babf71e..c0ccade 100644 --- a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherAppViewModel.kt +++ b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherAppViewModel.kt @@ -1,9 +1,8 @@ package org.jetbrains.plugins.template.weatherApp.services import com.intellij.openapi.Disposable -import com.intellij.openapi.application.EDT import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch @@ -59,6 +58,8 @@ class WeatherAppViewModel( private val weatherService: WeatherForecastServiceApi, ) : MyLocationsViewModelApi, WeatherViewModelApi { + private var currentWeatherJob: Job? = null + private val myLocations = MutableStateFlow(myInitialLocations) private val selectedLocationIndex = MutableStateFlow(myLocations.value.lastIndex) @@ -124,7 +125,9 @@ class WeatherAppViewModel( } override fun onLoadWeatherForecast(location: Location) { - viewModelScope.launch { + currentWeatherJob?.cancel() + + currentWeatherJob = viewModelScope.launch { val weatherForecastData = weatherService.loadWeatherForecastFor(location).getOrNull() ?: return@launch _weatherForecast.value = weatherForecastData diff --git a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherForecastService.kt b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherForecastService.kt index 8b52566..d5ff58b 100644 --- a/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherForecastService.kt +++ b/src/main/kotlin/org/jetbrains/plugins/template/weatherApp/services/WeatherForecastService.kt @@ -3,6 +3,7 @@ package org.jetbrains.plugins.template.weatherApp.services import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext +import kotlinx.coroutines.yield import org.jetbrains.plugins.template.weatherApp.model.* import java.time.LocalDate import java.time.LocalDateTime @@ -45,10 +46,13 @@ class WeatherForecastService( private suspend fun getWeatherData(location: Location): WeatherForecastData { val currentTime = LocalDateTime.of(LocalDate.now(), getRandomTime()) + yield() // Check cancellation + // Generate 7-day forecast data val dailyForecasts = generateDailyForecasts(currentTime) - // Simulates a network request + // Simulates a network request and stops the execution in case the coroutine + // that launched the getWeatherData task is canceled delay(100) return WeatherForecastData(