Last active
November 28, 2018 13:30
-
-
Save diefferson/3e7e27d88eb0b890b22d42b0416874ab to your computer and use it in GitHub Desktop.
CoroutinesUtils
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
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 ?: "")) | |
} | |
} | |
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
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