Exercise: CommentService
Implement the following functions from the CommentService
class:
addComment
- should read a user id from a token, transform the body to a CommentDocument
, and add it to the comment repository.getComments
- should get comments with users and return them as a collection.
class CommentService(
private val commentRepository: CommentRepository,
private val userService: UserService,
private val commentFactory: CommentFactory
) {
suspend fun addComment(
token: String,
collectionKey: String,
body: AddComment
) {
TODO()
}
suspend fun getComments(
collectionKey: String
): CommentsCollection = TODO()
}
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in coroutines/comment/CommentService.kt. You can find there starting code.
You can assume that findUserById
from userService
can be called multiple times for the same user id because it is cached. Alternatively, you can refactor this service to make sure it is not called more than once for the same id by the same getComments
call. The second option is more complex.
Once you are done with the exercise, you can check your solution here.
import domain.comment.*
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
class CommentService(
private val commentRepository: CommentRepository,
private val userService: UserService,
private val commentFactory: CommentFactory
) {
suspend fun addComment(
token: String,
collectionKey: String,
body: AddComment
) {
TODO()
}
suspend fun getComments(
collectionKey: String
): CommentsCollection = TODO()
}
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.