Skip to content

Instantly share code, notes, and snippets.

@FilipeLipan
Last active March 13, 2020 14:21
Show Gist options
  • Save FilipeLipan/30dcf49fe9ff00da893d8fbf8d09cd18 to your computer and use it in GitHub Desktop.
Save FilipeLipan/30dcf49fe9ff00da893d8fbf8d09cd18 to your computer and use it in GitHub Desktop.
abstract class UseCase<out Type, in Params> where Type : Any? {
abstract suspend fun run(params: Params): Either<Failure, Type>
suspend operator fun invoke(params: Params, coroutinesDispatcherProvider: CoroutinesDispatcherProvider, onResult: (Either<Failure, Type>) -> Unit = {}) {
val result = run(params)
withContext(coroutinesDispatcherProvider.main) {
onResult(result)
}
}
suspend operator fun invoke(coroutinesDispatcherProvider: CoroutinesDispatcherProvider, onResult: (Either<Failure, Type>) -> Unit = {}) {
val result = run(None() as Params)
withContext(coroutinesDispatcherProvider.main) {
onResult(result)
}
}
class None
}
class NewUkSignInViewModel(
val getSupportedCountriesUseCase: GetSupportedCountriesUseCase,
val coroutinesDispatcherProvider: CoroutinesDispatcherProvider) : BaseViewModel(), CoroutineScope {
private val executionJob: Job by lazy { Job() }
override val coroutineContext: CoroutineContext by lazy {
Dispatchers.Default + executionJob
}
val countriesAvailableNames: MutableLiveData<String> = mutableLiveData()
val errorEvent: SingleLiveData<String> = singleLiveData()
init {
loadCountries()
}
fun loadCountries(){
this.launch {
getSupportedCountriesUseCase(coroutinesDispatcherProvider) {
it.fold(::showError, ::showCountries)
}
}
}
private fun showError(failure: Failure){
print("error")
errorEvent.value = failure.toString()
}
private fun showCountries(result: List<Country>) {
val countriesViewDataList = result.map {
it.id
}.toString()
print("1 success")
countriesAvailableNames.value = countriesViewDataList
}
}
open class CoroutinesDispatcherProvider {
open val main: CoroutineContext by lazy { Dispatchers.Main }
open val io: CoroutineContext by lazy { Dispatchers.IO }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment