I create a background task to refresh the token fo...
# android
k
I create a background task to refresh the token for user but it throw NPE even though I have cast the variable in the end. Anyone know what I should do?
Copy code
private 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
    }
m
I'm going to assume that the
enqueue
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.
☝️ 1