Last active
March 17, 2022 18:22
-
-
Save klemensz/9122faa67124e1068086360ab3411d21 to your computer and use it in GitHub Desktop.
Fetch data with an observed location and a timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeViewModel(private val locationRepository: LocationRepository) : ViewModel() { | |
// ... | |
private suspend fun fetchFromRemote() { | |
// Initialize some variables: | |
var gotObservedLocation = false // Did we get an observed location? | |
var isTimeout = false // Will be set to true once the timeout is reached | |
var timeoutMs = 500L // Timeout in ms | |
// Observe the lastLocation | |
locationRepository.lastLocation.observeOnce { | |
gotObservedLocation = true | |
if (!isTimeout) { | |
// Only call fetchFromRemoteWithLocation(location) if we haven't run into a timeout yet | |
Timber.d("fetchFromRemote - observeOnce got $it") | |
runBlocking { | |
fetchFromRemoteWithLocation(it) | |
} | |
} | |
} | |
// Now, do the delay | |
delay(timeoutMs) | |
// OK... delay reached | |
isTimeout = true | |
if (!gotObservedLocation) { | |
// We didn't get an observed location before, so let's use the latest value (might be null) | |
Timber.d("fetchFromRemote timeout - got no observed location") | |
val currentLocation = locationRepository.lastLocation.value | |
fetchFromRemoteWithLocation(currentLocation) | |
} else { | |
// We already called fetchFeedHomeFromRemote(location) in the observer, nothing left to do | |
Timber.d("fetchFromRemote timeout - got observed location before timeout") | |
} | |
} | |
/** | |
* This is the function that actually fetches the data with a given location | |
* @param currentLocation the location to be sent with the API request - optional | |
*/ | |
private suspend fun fetchFromRemoteWithLocation(currentLocation: Location?) { | |
// Call some method to fetch data from the repository/API/... | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment