Код: Выделить всё
val locations = MutableStateFlow(emptyList())
private val _locations = MutableStateFlow(emptyList())
val locations: StateFlow
get() = _locations.asStateFlow()
private val userLocation: StateFlow = flow {
while (currentCoroutineContext().isActive) {
Timber.v("Updating user location")
emit(getLocation())
delay(15000L)
}
}.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000L),
null
)
init {
viewModelScope.launch {
combine(userLocation, cachedLocations) { androidLocation, cachedLocations ->
Timber.v("Updating sortable locations")
_locations.emit(getSortedLocations(androidLocation, cachedLocations))
}.collect()
}
}
fun updateLocations() {
viewModelScope.launch {
Timber.v("Updating sortable locations")
val androidLocation = getLocation()
val cachedLocations = cachedLocations.value
locations.value = getSortedLocations(androidLocation, cachedLocations)
}
}
Код: Выделить всё
@Composable
fun Screen() {
val locations by viewModel.locations.collectAsStateWithLifecycle()
}
Подробнее здесь: https://stackoverflow.com/questions/784 ... n-in-backg