Skip to content

Instantly share code, notes, and snippets.

@qwert2603
Created June 2, 2022 17:49
Show Gist options
  • Save qwert2603/edfaed09b06d980537bc8473df0b44b5 to your computer and use it in GitHub Desktop.
Save qwert2603/edfaed09b06d980537bc8473df0b44b5 to your computer and use it in GitHub Desktop.
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