Created
June 2, 2022 17:49
-
-
Save qwert2603/edfaed09b06d980537bc8473df0b44b5 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
package com.qwert2603.myapplication | |
import androidx.annotation.CheckResult | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.runBlocking | |
class Storage { | |
suspend fun get(): Result<String> = runCatching { | |
delay(1) | |
"smth" | |
} | |
@CheckResult | |
suspend fun save(s: String): Result<Unit> = runCatching { | |
delay(2) | |
} | |
} | |
class Service { | |
suspend fun get(): Result<String> = runCatching { | |
delay(3) | |
"anth" | |
} | |
} | |
inline fun <T> Result<T>.recoverCatching( | |
onError: (Throwable) -> Result<T>, | |
): Result<T> = if (isSuccess) this else onError(exceptionOrNull()!!) | |
inline fun <T> Result<T>.onSuccessCatching( | |
onSuccess: (T) -> Result<Unit>, | |
): Result<T> { | |
val value = getOrNull() | |
return if (value != null) { | |
onSuccess(value).map { value } | |
} else { | |
this | |
} | |
} | |
class Interactor( | |
private val storage: Storage, | |
private val service: Service, | |
) { | |
suspend fun go(): Result<String> = | |
service.get() | |
.onSuccessCatching { storage.save(it) } | |
// .onSuccess { storage.save(it) } | |
.recoverCatching { storage.get() } | |
} | |
fun main() { | |
runBlocking { | |
val interactor = Interactor(Storage(), Service()) | |
interactor.go() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment