Helper function to log from anywhere in the app :
fun log(
message: String,
tag: String? = null,
isError: Boolean = false,
buildType: String
)-
when
isErroris passed astrue, log is printed on the error stream otherwise on the info stream. -
buildTypeis taken as input to decide whether log should be printed. Pass your app'sBuildConfig.BUILD_TYPE, which if equals"debug"then only log is printed.
If
BuildConfigclass is not resolved, setandroid.buildFeatures.buildConfigtotruein your app's Gradle file and rebuild the project.
Helper function to get a CoroutineContext in built with exception handling :
fun defaultContext(
tag: String? = null,
onExceptionOccurred: (Throwable) -> Unit = {},
buildType: String
): CoroutineContext- uses
Dispatchers.IOby default
When exception occurs,
-
exception message & stack trace is logged (if
"debug"buildType) -
onExceptionOccurredlambda is invoked
Or if you prefer to get only an exception handler, call this function :
fun defaultExceptionHandler(
tag: String? = null,
onExceptionOccurred: (Throwable) -> Unit = {},
buildType: String
): CoroutineExceptionHandlerUsing the CoroutineContext & ExceptionHandler returned by the above described unctions, if you want to execute a suspend lambda, use this function :
fun defaultExecuteHandlingError(
tag: String? = null,
onExceptionOccurred: (Throwable) -> Unit = {},
lambda: suspend CoroutineScope.() -> Unit,
buildType: String
)
defaultContext(),defaultExceptionHandler(),defaultExecuteHandlingError()functions might be useful in different Android components other thanActivity&ViewModel(becauseBaseActivity&BaseViewModelhelper functions can be accessed there) likeService,BroadcastReceiveretc.