Skip to content

Instantly share code, notes, and snippets.

@diefferson
Last active November 28, 2018 13:30
Show Gist options
  • Save diefferson/3e7e27d88eb0b890b22d42b0416874ab to your computer and use it in GitHub Desktop.
Save diefferson/3e7e27d88eb0b890b22d42b0416874ab to your computer and use it in GitHub Desktop.
CoroutinesUtils
package br.com.futmundi.app.util
import br.com.myapp.data.repository.exception.KnownError
import br.com.myapp.data.repository.exception.KnownException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.android.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
fun <T> CoroutineScope.safeAsync(action: suspend () -> T,
onError: (e: Throwable) -> Unit = {},
onSuccess: (T) -> Unit = {}) = launch {
try {
val response = action()
withContext(kotlinx.coroutines.Dispatchers.Main) {
onSuccess(response)
}
} catch (e: Exception) {
withContext(kotlinx.coroutines.Dispatchers.Main) {
onError(e)
}
} catch (e: OutOfMemoryError) {
onError(KnownException(KnownError.OUT_OF_MEMORY_ERROR, e.message ?: ""))
}
}
fun CoroutineScope.safeLaunch(action: suspend () -> Unit,
onError: (e: Throwable) -> Unit = {},
onComplete: () -> Unit = {}) = launch {
try {
action()
withContext(kotlinx.coroutines.Dispatchers.Main) {
onComplete()
}
} catch (e: Exception) {
withContext(kotlinx.coroutines.Dispatchers.Main) {
onError(e)
}
} catch (e: OutOfMemoryError) {
onError(KnownException(KnownError.OUT_OF_MEMORY_ERROR, e.message ?: ""))
}
}
val user = MutableLiveData<User>()
fun getUser() = safeAsync({userRepository.loadUser()},
onError = {
viewStateEvent.value = ViewState.Error(R.string.load_user_error)
}, onSuccess = {
user.value = it
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment