https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

ahulyk

01/31/2019, 2:39 PM
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

streetsofboston

01/31/2019, 2:41 PM
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

ahulyk

01/31/2019, 2:47 PM
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

streetsofboston

01/31/2019, 2:53 PM
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

ahulyk

01/31/2019, 2:56 PM
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

streetsofboston

01/31/2019, 3:02 PM
Yep. And retrofit may use its own (IO) Dispatcher.
a

ahulyk

01/31/2019, 3:20 PM
Under the hood OkHttpClient uses new Thread() for network request - that is for sure
l

louiscad

01/31/2019, 3:36 PM
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

streetsofboston

01/31/2019, 3:56 PM
Parsing doesn’t necessarily involve network communication. It maybe just parsing a string that is in memory
a

ahulyk

01/31/2019, 4:07 PM
Looks like CoroutineCallAdapterFactory did the trick here 🙂
It uses Call callback. So Retrofit work asynchronous in that case!
Thank you!
g

gildor

02/01/2019, 6:47 AM
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

ahulyk

02/01/2019, 9:01 AM
Yeap.
6 Views