Hi) I'm a bit confused about coroutines on Android...
# coroutines
a
Hi) I'm a bit confused about coroutines on Android: Example 1:
Copy code
launch(IO) {
            val result = repoRepository.getAllRepos()
            withContext(Main) {
                textField.text = result
            }
        }
Example 2:
Copy code
launch(Main) {
            val result = repoRepository.getAllRepos()
            withContext(Main) {
                textField.text = result
            }
        }
Question is why i'm not getting android.os.NetworkOnMainThreadException in second example?
s
Does
getAllRepose()
do the actual fetching from the network, or does it just block and waits for an other thread, that does the networking, to return the result.
a
getAllRepose()
do the actual fetching from the network:
Copy code
class RepoRepositoryImpl @Inject constructor(
        private val apiService: APIService
) : RepoRepository {

    override suspend fun getAllRepos(orgName: String) : List<RepoDto> {
        return apiService.getAllRepos(orgName).await()
    }

}
s
But
apiService.getAllRepos()
does all the work, maybe on a different thread.
The
RepoRepositoryImpl.getAllRepos()
may just wait (await()) for that other thread to return the result
a
APIService is just Retrofit Service:
Copy code
interface APIService {

    @GET("/orgs/kotlin/repos")
    fun getAllReposRx(): Single<List<RepoDto>>

    @GET("/orgs/{org}/repos")
    fun getAllRepos(@Path("org") orgName: String): Deferred<List<RepoDto>>

}
s
Yep. And retrofit may use its own (IO) Dispatcher.
a
Under the hood OkHttpClient uses new Thread() for network request - that is for sure
l
There's no network on the main thread that would block it, there's just a coroutine suspending until some stuff done on another thread/dispatcher/executor completes and resumes it (and that stuff happens to do network I/O)
s
Parsing doesn’t necessarily involve network communication. It maybe just parsing a string that is in memory
a
Looks like CoroutineCallAdapterFactory did the trick here 🙂
It uses Call callback. So Retrofit work asynchronous in that case!
Thank you!
g
Under the hood OkHttpClient uses new Thread() for network request - that is for sure
This is not exactly correct, OkHttp uses own dispatcher with thread pool
a
Yeap.