Last active
March 10, 2022 18:44
-
-
Save rommansabbir/0c14f3e7a014d4578727662ef4f52fd9 to your computer and use it in GitHub Desktop.
A generic API to execute a given body and return an object [T] type. If exception occur return null else the object [T].
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 GenericBodyExecutor { | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
println(executeBodyOrReturnNull<Int> { GenericData("0").data.toInt() }) // Result -> 0 | |
println(executeBodyOrReturnNull<Int> { GenericData("Hello").data.toInt() }) // Result -> null | |
} | |
} | |
} | |
data class GenericData(val data: String) | |
/** | |
* A generic API to execute a given body and return an object [T] type. | |
* If exception occur return null else the object [T]. | |
* | |
* @param T Object type. | |
* @param body Code block to be executed under try catch and should return [T]. | |
* | |
* @return [T] object can be nullable. | |
*/ | |
inline fun <T> executeBodyOrReturnNull(crossinline body: () -> T): T? { | |
return try { | |
body.invoke() | |
} catch (e: Throwable) { | |
e.printStackTrace() | |
null | |
} | |
} | |
suspend inline fun <T> executeBodyOrReturnNullIOScope(crossinline body: CoroutineScope.() -> T): T? { | |
return withContext(Dispatchers.IO) { | |
try { | |
body.invoke(this) | |
} catch (e: Exception) { | |
e.printStackTrace() | |
null | |
} | |
} | |
} | |
inline fun <T> executeBodyOrReturnNull( | |
crossinline body: () -> T, | |
crossinline errorBody: (Exception) -> Unit = {} | |
): T? { | |
return try { | |
body.invoke() | |
} catch (e: Exception) { | |
errorBody.invoke(e) | |
null | |
} | |
} | |
suspend inline fun <T> executeBodyOrReturnNullIOScope( | |
crossinline body: CoroutineScope.() -> T, | |
crossinline errorBody: (Exception) -> Unit = {} | |
): T? { | |
return withContext(Dispatchers.IO) { | |
try { | |
body.invoke(this) | |
} catch (e: Exception) { | |
errorBody.invoke(e) | |
null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment