I'm using data store ( because it's better than shared preferences ) to store the token. In intercept function override by Interceptor I want to get the token from data store but not to use runBlocking. I used runBlocking and it worked but my PM doesn't want to use runBlocking . You guys have any ideas to replace runBlocking ?
I was asked Chat GPT but the solution be answered is :
fun fetchTokenFromDataStore(): Deferred<String> = coroutineScope {
async {
// Fetch the token from data store asynchronously
// Replace this with your actual logic to fetch the token
delay(1000) // Simulating an async operation
return@async "your_token_here"
}
}
fun makeHttpRequestWithToken(token: String) {
val client = OkHttpClient()
val request = Request.Builder()
.url("your_request_url_here")
.header("Authorization", "Bearer $token")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle failure
}
override fun onResponse(call: Call, response: Response) {
// Handle response
}
})
}
// Usage
fun performHttpRequest() {
// Fetch the token asynchronously
val tokenDeferred = fetchTokenFromDataStore()
// Once the token is fetched, initiate the HTTP request
tokenDeferred.invokeOnCompletion { throwable ->
if (throwable == null) {
val token = tokenDeferred.getCompleted()
makeHttpRequestWithToken(token)
} else {
// Handle error
}
}
}
I know it wrong but I have no idea to do that. You guys please help me!