
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. ThetoFakturowniaInvoiceDatafunction is a simple mapping.sendEmail- prepares an email and sends it using theapimethod of theSendGridclass. This is a blocking operation that returns aResponseobject.getUserOrders- gets orders made by the user from the database using the MongoDB Kotlin driver.toListis 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.