Sudhir Singh Khanger
06/28/2021, 2:13 PMRetrofit
call without suspend keyword from a Coroutine
?uli
06/28/2021, 2:39 PMIan Lake
06/28/2021, 3:14 PMSudhir Singh Khanger
06/28/2021, 4:14 PMsomeOtherFunction()
not be called if I don't use suspend
function?
viewModelScope.launch {
launch { non-suspending-retrofit }
someOtherFunction()
}
4. In a scope everything is already synchronous so even if it blocks the non-ui thread I am not sure if that matters. Enlighten me please.
5. Is logging the best way to detect blocking calls?Zach Klippenstein (he/him) [MOD]
06/28/2021, 5:15 PMsomeOtherFunction()
will run first and then one the coroutine starts, then it will block its thread.
4. A good rule is that the only time it’s safe to block a coroutine for IO work is if you’re running on the IO dispatcher.
5. Logging won’t automatically detect blocking calls. I don’t know of any generic way to detect blocking calls other than mechanisms very specific to Android’s main thread (i.e. ANR detection).gildor
06/28/2021, 11:41 PMZach Klippenstein (he/him) [MOD]
06/28/2021, 11:57 PMjw
06/29/2021, 1:42 AMgildor
06/29/2021, 2:35 AMsuspend
to return result directly, without Calljw
06/29/2021, 2:40 AMSudhir Singh Khanger
06/29/2021, 9:03 AMBut the real question is why do you need this?
this all seems like kind of a pointless discussionI am not using Retrofit in a Coroutine without
suspend
keyword. I was asked as to why I have marked a function as suspend
when I could use it without one.
I wish I could just say to just use it because it is a good thing. I need to justify its usage with code and solid argument. I can't present it like a black magic.gildor
06/29/2021, 9:06 AMSudhir Singh Khanger
06/29/2021, 9:16 AMsuspend
keyword.gildor
06/29/2021, 9:21 AMZach Klippenstein (he/him) [MOD]
06/29/2021, 11:09 AMCall
, i think your question could be interpreted to be about two different things:
1. What’s the difference between synchronous, blocking APIs and asynchronous, non-blocking ones? Eg Call.execute
vs Call.enqueue
2. What’s the difference between using coroutines for asynchronous requests vs other async apis like Call.enqueue
?
With your clarification, if I understand correctly, it sounds like you’re not really asking about retrofit specifically, and your question is more (1), ie “Why use an API that allows for non-blocking asynchrony vs one that blocks?”
That is a pretty large question but one that has been discussed extensively. In Java (and many other programming languages), the answer basically comes down to “because OS threads are expensive and it’s a lot cheaper and more flexible to manage asynchrony in userspace”. In most traditional languages the only way to do this is via callbacks, but languages like Kotlin, Swift, Python, C#, etc have all introduced various forms of syntactic sugar (eg coroutines, async/await) to make working with callbacks easier and less boilerplatey and support stuff like cancellation.