Kiki Abdullah
06/13/2022, 2:18 PMprivate var result: Result? = null
private lateinit var data: Data
override fun doWork(): Result {
val refreshToken = inputData.getString(REFRESH_TOKEN)
APIConfig.getAuthAPIService().refreshToken("refreshToken=$refreshToken")
.enqueue(object : Callback<LoginResponse> {
override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
if (response.isSuccessful) {
val token = response.body()?.loginData?.accessToken.toString()
Log.e("token from TokenWorker ", token)
data = workDataOf(NEW_TOKEN to token)
result = Result.success(data)
}
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
Log.e(TAG, "onFailure: ${t.message}")
result = Result.failure()
}
})
return result as Result
}
mkrussel
06/13/2022, 2:32 PMenqueue
call is doing asynchronous work. That means the function returns before the callback gets called.
doWork
probably needs to be a suspending function and you need to use https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html to wait for the callback to happen.