Skip to content

Commit 9f33527

Browse files
committed
ref: UseCase class improvement and extra doc/comments
1 parent 80f6da7 commit 9f33527

File tree

1 file changed

+28
-10
lines changed
  • app/src/main/kotlin/com/fernandocejas/sample/core/interactor

1 file changed

+28
-10
lines changed

app/src/main/kotlin/com/fernandocejas/sample/core/interactor/UseCase.kt

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,32 +17,50 @@ package com.fernandocejas.sample.core.interactor
1717

1818
import com.fernandocejas.sample.core.failure.Failure
1919
import com.fernandocejas.sample.core.functional.Either
20-
import kotlinx.coroutines.*
20+
import kotlinx.coroutines.CoroutineScope
21+
import kotlinx.coroutines.Dispatchers
22+
import kotlinx.coroutines.MainScope
23+
import kotlinx.coroutines.async
24+
import kotlinx.coroutines.launch
2125

2226
/**
23-
* Abstract class for a Use Case (Interactor in terms of Clean Architecture).
24-
* This abstraction represents an execution unit for different use cases (this means that any use
25-
* case in the application should implement this contract).
27+
* Abstract class for a Use Case (Interactor in terms of
28+
* Clean Architecture naming convention).
2629
*
27-
* By convention each [UseCase] implementation will execute its job in a background thread
28-
* (kotlin coroutine) and will post the result in the UI thread.
30+
* This abstraction represents an execution unit for
31+
* different use cases (this means that any use case
32+
* in the application should implement this contract).
33+
*
34+
* By convention each [UseCase] implementation will
35+
* execute its job in a pool of threads using
36+
* [Dispatchers.IO].
37+
*
38+
* The result of the computation will be posted on the
39+
* same thread used by the @param 'scope' [CoroutineScope].
2940
*/
3041
abstract class UseCase<out Type, in Params> where Type : Any {
3142

3243
abstract suspend fun run(params: Params): Either<Failure, Type>
3344

3445
operator fun invoke(
3546
params: Params,
36-
scope: CoroutineScope = GlobalScope,
47+
scope: CoroutineScope = MainScope(),
3748
onResult: (Either<Failure, Type>) -> Unit = {}
3849
) {
39-
scope.launch(Dispatchers.Main) {
40-
val deferred = async(Dispatchers.IO) {
50+
scope.launch {
51+
val deferredJob = async(Dispatchers.IO) {
4152
run(params)
4253
}
43-
onResult(deferred.await())
54+
onResult(deferredJob.await())
4455
}
4556
}
4657

58+
/**
59+
* Helper class to represent Empty
60+
* Params when a use case does not
61+
* need them.
62+
*
63+
* @see UseCase
64+
*/
4765
class None
4866
}

0 commit comments

Comments
 (0)