I have some code that can mostly run on a worker thread but one single line must run on the UI thread.
So I used to have this code that gave a lot of ANRs.
<code>methodOnWorkerThread(){
..some calls...
runOnUIThread{
..some more calls...
callThatRequiresTheUIThreadAndGivesANRs()
}
}
</code>
<code>methodOnWorkerThread(){
..some calls...
runOnUIThread{
..some more calls...
callThatRequiresTheUIThreadAndGivesANRs()
}
}
</code>
methodOnWorkerThread(){
..some calls...
runOnUIThread{
..some more calls...
callThatRequiresTheUIThreadAndGivesANRs()
}
}
I changed that code to be:
<code>methodOnWorkerThread(){
..some calls...
..some more calls...
runBlocking(Dispatchers.Main) {
callThatRequiresTheUIThreadAndGivesANRs()
}
}
</code>
<code>methodOnWorkerThread(){
..some calls...
..some more calls...
runBlocking(Dispatchers.Main) {
callThatRequiresTheUIThreadAndGivesANRs()
}
}
</code>
methodOnWorkerThread(){
..some calls...
..some more calls...
runBlocking(Dispatchers.Main) {
callThatRequiresTheUIThreadAndGivesANRs()
}
}
And with that all my ANRs went away.
I realize ..some more calls...
could be the culprit but all the ANR stack traces had callThatRequiresTheUIThreadAndGivesANRs()
.
So is there a difference as far as ANRs are concerned between runOnUIThread
and runBlocking(Dispatchers.Main)
?