Я новичок в Android, поправьте меня, если я ошибаюсь.
Я переключаю диспетчер с помощью withContext, нужно ли нам переключаться?
Код: Выделить всё
@HiltViewModel
class TrainVM @Inject constructor(
private val repo: Repository, // Inject the repository
private val apiRepo: KtorRepo
) : ViewModel() {
private var localSchCache = mutableMapOf()
private var trainSchCache = mutableMapOf()
private val _trainStatus =
MutableStateFlow(value = ViewState.Loading)
val trainStatus = _trainStatus.asStateFlow()
private val _isLoading = MutableStateFlow(true)
val isLoading = _isLoading.asStateFlow()
fun fetchTrain(train: String, isLive: Boolean, date: LocalDate?) {
_isLoading.update { true }
_trainStatus.update { ViewState.Loading }
if (isLive) {
loadTrainStatus(train, date = date) //loads live status using API data
} else {
loadSchedule(train = train) // loads data from room
}
}
//////////////////////////////////////////
private fun loadSchedule(
train: String,
) {
viewModelScope.launch {
try {
withContext(Dispatchers.IO) {
val localSch = localSchCache[train] ?: repo.getSch(train)
.also { localSchCache[train] = it }
val trainSch = trainSchCache[train]
?: mappedTrainToStation(localSch).also {
trainSchCache[train] = it
}
_trainStatus.update { ViewState.Success(data = trainSch) }
}
} catch (exception: Exception) {
_trainStatus.update {
ViewState.Error(
message = exception.message ?: "An unknown error occurred"
)
}
} finally {
_isLoading.update { false }
}
}
}
private fun loadTrainStatus(
train: String,
date: LocalDate? = null,
) {
viewModelScope.launch {
try {
val localData = localSchCache[train] ?: repo.getSch(train)
.also { localSchCache[train] = it }
apiRepo.fetchTrainStatus(train).onSuccess { apiData ->
val mappedData = mappedTrainToStation(localData, apiData)
_trainStatus.update { ViewState.Success(data = mappedData) }
}.onFailure { exception ->
_trainStatus.update {
ViewState.Error(
message = exception.message ?: "An unknown error"
)
}
}
} catch (exception: Exception) {
_trainStatus.update {
ViewState.Error(
message = exception.message ?: "An unknown error occurred"
)
}
} finally {
_isLoading.update { false }
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... view-model
Мобильная версия