Background

When using the awaitExchange extension function on a Kotlin project, I've missed the presence of a awaitExchangeOrNull function, that would receive a function returning T?. I've added it to my project, but I think it would be nice to have it on the lib aswell, since I believe it is a usefull extension function.

Changes

I've simple added a new extension function awaitExchangeOrNull and two test scenarios.

This is my first time attempting to contribute to an open source repository, so, feel free to correct me or suggest changes, I will gladly adhere to suggestions. And let me know if this isn't desired.

Comment From: pivotal-issuemaster

@gabrielerzinger Please sign the Contributor License Agreement!

Click here to manually synchronize the status of this Pull Request.

See the FAQ for frequently asked questions.

Comment From: pivotal-issuemaster

@gabrielerzinger Thank you for signing the Contributor License Agreement!

Comment From: gabrielerzinger

@sdeleuze i saw that you were the one who recently changed those files, do you think this makes sense?

Comment From: sdeleuze

Thanks for your contribution, I need to have a deeper look but it seems to make sense indeed.

Comment From: rgmz

Hey @sdeleuze, are there any updates or blockers on this?

To expand on @gabrielerzinger's use-case, prior to 5.2 (when awaitExchange() was deprecated), it was possible to write the following code:

// Check whether the role already exists.
val existing = client.get().uri("/api/roles/${role.id}")
    .awaitExchange()
    .let {
        when (val status = it.statusCode()) {
            HttpStatus.OK -> it.awaitBodyOrNull<Role>()
            HttpStatus.NOT_FOUND -> null
            else -> {
                val resp = it.awaitBodyOrNull<String>()
                throw IllegalStateException("Unexpected response from '/api/roles/${role.id}': status=$status, body=$resp")
            }
        }
    }

Because awaitExchange { } doesn't have a nullable counterpart, it's not possible to represent the same logic. I was actually in the midst of upgrading a project when I came across this issue.

Let me know if there's any way I can help get this merged.