Last active
May 22, 2018 14:02
-
-
Save npatarino/1ac4d0f97adfaafbf5cd00de732afc59 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface TasksRepository { | |
suspend fun tasks(user: User): Either<RepositoryError, List<Task>> | |
} | |
fun tasks(tasksRepository: TasksRepository, userRepository: UserRepository): | |
() -> Either<RepositoryError, List<Task>> = { | |
runBlocking { tasksRepository.tasks(userRepository.currentUser()) } // This is b | |
} | |
UseCase<RepositoryError, List<Task>>().bg(tasks(tasksRepository, userRepository)) | |
.ui { | |
it.fold({ handleError() }, { handleSuccess(it) }) | |
}.run(AndroidExecutor()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UseCase<Error, Result> { | |
fun bg(background: () -> Either<Error, Result>, delay: Long = 0): Then<Error, Result> = | |
Then(background, delay) | |
} | |
interface UseCaseExecutor { | |
fun <Error, Result> execute(background: () -> Either<Error, Result>, | |
ui: (Either<Error, Result>) -> Unit, | |
delayed: Long = 0): CancellationToken | |
} | |
class CoroutineExecutor : UseCaseExecutor { | |
override fun <Error, Result> execute(background: () -> Either<Error, Result>, | |
ui: (Either<Error, Result>) -> Unit, | |
delayed: Long): CancellationToken = | |
JobCancellationToken(launch { | |
delay(delayed) | |
ui(background()) | |
}) | |
} | |
class SyncCoroutineExecutor : UseCaseExecutor { | |
override fun <Error, Result> execute(background: () -> Either<Error, Result>, | |
ui: (Either<Error, Result>) -> Unit, | |
delayed: Long): CancellationToken = JobCancellationToken(runBlocking { | |
val job = launch { delay(delayed); ui(background()) } | |
job.join() | |
job | |
}) | |
} | |
class AndroidExecutor : UseCaseExecutor { | |
override fun <Error, Result> execute(background: () -> Either<Error, Result>, | |
ui: (Either<Error, Result>) -> Unit, delayed: Long): | |
CancellationToken { | |
doAsync { | |
val result = background() | |
uiThread { | |
ui(result) | |
} | |
} | |
return CancellationToken.empty | |
} | |
} | |
interface CancellationToken { | |
fun cancel(message: String = ""): Boolean | |
companion object { | |
val empty = object : CancellationToken { override fun cancel(message: String): Boolean = true } | |
} | |
} | |
class JobCancellationToken(private val job: Job) : CancellationToken { | |
override fun cancel(message: String): Boolean = job.cancel() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment