0

I have an API that returns the network status and I want to add retry and cancel function for the API call

@GET("{path1}/{path2}")
suspend fun status(
    @HeaderMap headers: Map<String, String>
): Status?

This is the service class from where the API is called

override suspend fun status(): Status? =
    service.status(
        path1 = PATH_ONE,
        path2 = PATH_TWO,
        headers = mapOf(
            USER_AGENT to userAgent,
            ACCEPT to accept,
            ACCEPT_LANGUAGE to locale,
            X_APP_GUID to xAppGuid
        )
    )

The issue that I am facing is that to use the retrofit2.enqueue() and retrofit2.cancel() functions I need to change the return type of the status() function to Call, but then I face the issue that I cannot return that to the user, because Call() is an interface and cannot instantiated, and I need to return the actual status.

Does anyone have any clue how to do it?

  • Suspend functions in Retrofit are cancellable by cancelling whatever coroutine has called them. You can cancel a coroutine by hanging onto the Job reference returned by `launch` in a property and calling cancel on it. – Tenfour04 Feb 01 '22 at 15:58

1 Answers1

1

When using Retrofit with Coroutines you do NOT need to use Call.

suspend functions (returned by Retrofit) are cancellable and will try to cancel the call when canceled. That means that:

myScope.launch { status(...) }

will be canceled whenever myScope is canceled. You can alternately keep a reference to the returned Job and cancel that yourself.

For retrying you can take a look at this answer

retryIO(times = 3) { status(...) }
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56