Exercise: Using dispatchers
For each of the functions below, decide if you need to set a dispatcher, and if so, which one:
createInvoice
- prepares an invoice and sends it to the SaaS API using the Retrofit library. In this library, we define suspending functions. The toFakturowniaInvoiceData
function is a simple mapping.sendEmail
- prepares an email and sends it using the api
method of the SendGrid
class. This is a blocking operation that returns a Response
object.getUserOrders
- gets orders made by the user from the database using the MongoDB Kotlin driver. toList
is a suspending function that returns a list of orders.upscaleImage
- a function that uses the TensorFlow library to upscale an image.
override suspend fun createInvoice(
invoiceData: InvoiceData,
) {
invoiceApi.postInvoice(
invoiceData.toFakturowniaInvoiceData()
)
}
interface InvoiceApi {
@POST("invoices.json")
suspend fun postInvoice(
@Body invoice: SendInvoiceData
): InvoiceCreationResponse
}
private val invoiceApi = retrofit2.Retrofit.Builder()
.baseUrl(invoiceBaseUrl)
.build()
.create(InvoiceApi::class.java)
private val sendGrid = SendGrid(API_KEY)
suspend fun sendEmail(email: Email) {
val request = Request().apply {
method = Method.POST
endpoint = "mail/send"
body = email.toSendGridEmail()
}
sendGrid.api(request)
}
private val orderCollection = mongoClient
.getDatabase("shop")
.getCollection<Order>("orders")
suspend fun getUserOrders(userId: String): List<Order> =
orderCollection
.find(eq("userId", userId))
.toList()
val model = TensorFlowModel()
suspend fun upscaleImage(image: Image): Image =
model.upscale(image)
Once you are done with the exercise, you can check your solution here.
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.