Result pattern with Coroutines
In my previous post, “The result pattern with Kotlin“, I introduced the result pattern, where it fits in the land of Kotlin and whether you should use it in your projects. This post will focus on how to integrate the result pattern with Kotlin coroutines using Result4K.
Kotlin was designed and written in such a way that we can utilise the power of Coroutines in a very familiar and simple way. Because of this, the result pattern, using Result4K, can be wired up quite easily (with caveat).
Lets build a house
Below, you can see the the BuilderService
. This service has a single public function called makeABuilding
. This function calls off to a number of suspended functions that build specific parts of our building. We want the service to do the following:
- Lay the foundations
- Build the walls
- Asynchronously:
- Put in the windows
- put in the doors
- put on the roof
1 |
|
This code looks fine, however, putInTheWindows()
, putInTheDoors()
and putOnTheRoof()
are not running asynchronously! By default, suspended functions run sequentially. Simply throwing suspended functions into the zip
function available in Result4K does not give us our desired behaviour.
Going asynchronous
We can write our own zipAsync
function to mimic that of the Result4K built-in to enable asynchronous execution. We will use Coroutine’s async
to produce Deferred results that are awaited on before calling out to the usual synchronous zip
.
1 |
|
We now get asynchronous resultified zipping! This is a step in the right direction but we are forcing ourselves to conform to adding extra boilerplate each time we call zipAsync
. Lets tidy this up a bit.
Make it look pretty
1 |
|
Now, we pass our suspended functions into our zipAsync
. Much better!
We still achieve our asynchronous execution in our slightly more wordy zipAsync
function, that will be hidden away in some utility file never to be seen again, and have cleaned up our call-site!
To have a play with the above examples, head over to the following Git repo