Upgrading to suspending functions

Let's now refactor the code to use suspending functions. We start with the same data class:

data class Profile(
val id: Long,
val name: String,
val age: Int
)

But instead of the verbose names, we can have cleaner ones. And even more important, instead of the interface forcing the implementation to be an async function, we only care about it suspending and returning a Profile – we can now remove Deferred from the equation:

interface ProfileServiceRepository {
suspend fun fetchByName(name: String) : Profile
suspend fun fetchById(id: Long) : Profile
}

The implementation can be easily converted, too. Right now it doesn't need to actually suspend; it's a mock after all:

class ProfileServiceClient : ProfileServiceRepository {
override suspend fun fetchByName(name: String) : Profile {
return Profile(1, name, 28)
}

override suspend fun fetchById(id: Long) : Profile {
return Profile(id, "Susan", 28)
}

}
A real implementation could use rxJava, retrofit, or any other library to do the actual request, without having to tie the interface ProfileServiceRepository to their implementation of futures.

Now the caller's code is a little bit cleaner:

fun main(args: Array<String>) = runBlocking {
val repository: ProfileServiceRepository = ProfileServiceClient()

val profile = repository.fetchById(12)
println(profile)
}

The output is the same as before:

This approach has some clear advantages over the async implementation:

  • Flexible: The details of the implementation are not leaked, so the implementation can be made using any library that supports futures. As long as the implementation doesn't block the current thread, and returns the expected Profile, any type of future will work.
  • Simpler: Using an async function for a task that we want to be sequential adds the verbosity of having to call await() all the time, and forces us to name the functions with explicitly async names. Using a suspending function removes both the need to change the name and the need to call await() each time the repository is used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.93.20