Skip to content

Instantly share code, notes, and snippets.

View GauravChaddha1996's full-sized avatar
🙂
Giving my best!

Gaurav Chaddha GauravChaddha1996

🙂
Giving my best!
View GitHub Profile
val job = launch {
// fire and forget task is done here
}
val deferredJob = async<Int> {
// a job which returns some result
}
// Block until deferredJob returns with the result
val result = deferredJob.await()
class MyViewModel : ViewModel(), CoroutineScope {
override val coroutineContext =
viewModelScope.coroutineContext + Dispatchers.Default
fun someF() {
launch {
// No need to write viewModelScope.launch
// and this is automatically on Dispatchers.Default
}
class MyViewModel: ViewModel() {
init {
viewModelScope.launch {
// Coroutine that will be cancelled
// when the ViewModel is cleared.
}
}
}
interface SomeApiService {
@GET("some_end_point")
fun getApiEndpointData(@QueryMap map:Map<String,String>): Call<ApiData>
}
val service = RetrofitHelper.createRetrofitService(SomeApiService::class.java)
// we pass the callback here
service.getApiEndpointData().enqueue()
interface SomeApiService {
@GET("some_end_point")
fun getApiEndpointData(@QueryMap map:Map<String,String>): Call<ApiData>
}
launch(coroutineExceptionHandler) {
val service = RetrofitHelper.createRetrofitService(SomeApiService::class.java)
val response = service.getApiEndpointData()
// Use the response here
}
val ceh = CoroutineExceptionHandler { _, throwable ->
launch (Dispatchers.Main) { showFailedUI() }
}
launch(Dispatchers.Default + ceh) {
val apiCall1Result = async {
val r1 = apiCall1()
if(r1.status=="failed") {
throw Exception("api call 1 fails")
}
}
val parentJob = scope.launch {
val result1 = suspendFunction1()
var nonCooperativeChildResult = 0
val nonCooperativeChild = launch {
while(isActive) {
nonCooperativeChildResult =
someRecursiveProcessing(nonCooperativeChildResult)
}
}
val result2 = async { someApiCallWithRetrofit() }
val eh = CoroutineExceptionHandler { _, throwable ->
println("Oops error occured: ${throwable.localizedMessage}")
}
launch(eh) {
async {
delay(100)
throw Exception("I failed)
}
val eh = CoroutineExceptionHandler { _, throwable ->
println("Oops error occured: ${throwable.localizedMessage}")
}
// Crashes the main thread since top most launch doesn't
// handle exception even if child coroutine does
launch {
delay(100)
launch(eh) {
throw Exception("I failed")
val eh = CoroutineExceptionHandler { _, throwable ->
println("Oops error occured: ${throwable.localizedMessage}")
}
launch(eh) {
delay(100)
throw Exception("I failed")
}
Output:
Oops error occured: I failed