Duchynko
09/30/2019, 7:25 AMMartin Nordholts
09/30/2019, 7:25 AMDuchynko
09/30/2019, 7:26 AMDuchynko
09/30/2019, 7:28 AMMartin Nordholts
09/30/2019, 7:33 AMGlobalScope.launch(Dispatchers.Main) {
val students = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { getStudents() }
recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
recyclerView.adapter = MainAdapter(students)
hideLoadingAnimation()
}
but you should really also use a proper CoroutineScope
for the coroutine, but let’s handle one issue at a time.Duchynko
09/30/2019, 7:39 AMDuchynko
09/30/2019, 7:41 AMDuchynko
09/30/2019, 7:43 AMgildor
09/30/2019, 8:51 AMhideLoadingAnimation
from coroutine with Main dispathcergildor
09/30/2019, 8:52 AMoverride fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.student_list)
showLoadingAnimation()
lifecycleScope.launch {
val students = getStudents()
recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
recyclerView.adapter = MainAdapter(students)
hideLoadingAnimation()
}
}
gildor
09/30/2019, 8:58 AMwithContext(Dispatchers.IO) { getStudents() }It’s not good style. Depends on how
getStudents()
implemented, if it’s blocking, better to make in suspend function, also if it’s network request no need to use IO dispatcher, better use some asyncronous http clientgildor
09/30/2019, 9:00 AMMartin Nordholts
09/30/2019, 9:02 AMIt’s not good style.If getStudents() is a “classical” Thread-blocking function call (which I assumed was the case here) it’s fine though, isn’t it? But yes even better if it would be a
suspend
function of course so there was no need for withContext
gildor
09/30/2019, 9:04 AMIf getStudents() is a “classical” Thread-blocking function call it’s fine though, isn’t it?In very general case it’s true, but in most cases it’s just some network request that doesn’t require blocking the thread And even so, and you control function better rename it to
getStudentsBlocking()
And even if you do not control it, better to abstract this function to some suspend wrapper before use it in your UICasey Brooks
09/30/2019, 3:15 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
block inside the HTTP call suspend wrapper, so that using it from your activity does not need to put it there