https://kotlinlang.org logo
#android
Title
# android
c

CamilleBC

10/02/2018, 8:50 AM
@gildor Thanks for the link ! My problem is that I don't really understand coroutines, I guess! 😄 I was setting up a simple app to update some values by making API calls in HTTP. I managed to communicate through the socket using coroutines, but as soon as I was trying to update the UI through callbacks, it became messy. That's why I thought of just creating one other thread for the network and not use coroutines. But I felt I was just going at it the wrong way, so that UI looks perfect to me! Thanks again 😉
g

gildor

10/02/2018, 8:52 AM
I managed to communicate through the socket using coroutines
Do you use sockets for HTTP requests?? Sounds like a super low level solution
c

CamilleBC

10/02/2018, 8:54 AM
I'm communcating with an API that I haven't built. I need to communicate with it, and it's running on the phone, on a local socket, and the API protocol is in RESTful HTTP. 🙂
g

gildor

10/02/2018, 8:57 AM
sure, every http server runs on socket, just curious which http client do you use for that? You just said that use “socket” and it’s usually means that you work with raw sockets what is sounds like too low level solution for HTTP
c

CamilleBC

10/02/2018, 9:01 AM
I just use HttpUrlConnection, no particular client, if that is what you mean?
g

gildor

10/02/2018, 9:03 AM
Okay, it’s more clear now. HttpUrlConnection is blocking API, just wrap all the calls to
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
, this will allow to use it without main thread blocking:
Copy code
fun loadSomething(url: URL) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    url.openConnection().getInputStream().readBytes()
}
c

CamilleBC

10/02/2018, 9:04 AM
Oh cool, I knew about
Dispatchers.Main
and
Dispatchers.Default
, not about this one. Thanks! I'm still learning how to get info from the docs, I'm pretty bad at that 😢
g

gildor

10/02/2018, 9:06 AM
You shouldn’t run blocking code on Default dispatcher, because it’s intended to use only with non-blocking operations
Official guide is very good, I highly recommend to read it too: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutines-guide.md
👍 2
🙌 2
c

CamilleBC

10/02/2018, 9:10 AM
Yes, I'm actually reading that thanks to the link you posted! I wasn't able to understand from the documentation but the guide is super cool!
g

gildor

10/02/2018, 9:39 AM
@elizarov I didn’t read updated guide recently, just curious, does guide contains part about wrapping blocking code? Looks as very common question, like in this thread
e

elizarov

10/02/2018, 9:44 AM
Not yet. We don’t have “wrapping IO” section. Writing it down to backlog, thanks.
👍 2
4 Views