
commonMain.io.github.gaaabliz.kliz.common.base.Operation.kt Maven / Gradle / Ivy
package io.github.gaaabliz.kliz.common.base
sealed class Operation (
data : T? = null,
errorMessage:String? = null,
) {
companion object {
fun isOk(operation : Operation) : Boolean {
return when(operation) {
is Success -> true
is Error -> false
}
}
fun exec(
operation : Operation,
onSuccess : (T) -> Unit,
onError : (String?) -> Unit,
) {
return when(operation) {
is Success -> onSuccess(operation.data)
is Error -> onError(operation.errorMessage)
}
}
fun execWithReturn(
operation : Operation,
onSuccess : (OI) -> Operation,
onError : (String?) -> Operation,
) : Operation {
return when(operation) {
is Success -> { return onSuccess(operation.data) }
is Error -> onError(operation.errorMessage)
}
}
fun getSuccessDataFrom(
operation: Operation,
onError : (String?) -> Unit,
onSuccess: (T?) -> Unit = {},
) : T? {
return when(operation) {
is Success -> {
onSuccess(operation.data)
operation.data
}
is Error -> {
onError(operation.errorMessage)
null
}
}
}
fun getSuccessDataFrom(
operation: Operation,
onError : (String?) -> Unit,
) : T? {
return when(operation) {
is Success -> operation.data
is Error -> {
onError(operation.errorMessage)
null
}
}
}
suspend fun exec(
operation : Operation,
onSuspendSuccess : suspend (T) -> Unit,
onError : (String?) -> Unit,
) {
return when(operation) {
is Success -> onSuspendSuccess(operation.data)
is Error -> onError(operation.errorMessage)
}
}
}
data class Success (
val data: T,
) : Operation(data, null)
data class Error (
val errorMessage: String?,
) : Operation(null, errorMessage) {
}
}
inline fun safeCall(action: () -> Operation): Operation {
return try {
action()
} catch (e: Exception) {
Operation.Error(e.message ?: "An unknown Error Occurred")
}
}
sealed class CustomOperation (
title : String? = null,
data : T? = null,
successMessage : String? = null,
errorMessage:String? = null,
) {
data class Success (
val title : String,
val successMessage : String? = null,
val data : T? = null,
) : CustomOperation(successMessage = successMessage, data = data, title = title)
data class Error (
val title : String,
val errorMessage : String,
) : CustomOperation(title = title, errorMessage = errorMessage)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy