svenjacobs
03/29/2021, 6:32 AMsuspend fun showSnackbar() {
val snackbar = Snackbar.make(...)
snackbar.show()
delay(4000)
snackbar.setAction("...", null) // crash here
snackbar.dismiss()
}
The functions is called via launch(Dispatchers.Main) { showSnackbar() }
. Please don't ask why I have to null
the action. It is required to prevent a false positive memory leak warning. Anyway, the call snackbar.setAction()
crashes the app with android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
and I wonder if delay()
might change the Dispatcher?? 🤔 Thanks for your help!delay()
in a withContext(Dispatchers.Main)
fixes the crash but I did not expect this behaviour 😕uli
03/29/2021, 7:04 AMLog.d("Thread", "On Thread ${Thread.currentThread}")
svenjacobs
03/29/2021, 7:10 AMuli
03/29/2021, 7:15 AMLog.d("Thread", "My Dispatcher is ${coroutineContext[CoroutineDispatcher]}")
louiscad
03/29/2021, 7:26 AMsvenjacobs
03/29/2021, 7:28 AMlaunch(Dispatchers.Main) { showSnackbar() }
uli
03/29/2021, 7:28 AMlaunch(Dispatchers.Main) { showSnackbar() }
svenjacobs
03/29/2021, 7:29 AMdelay()
and this is the output:
Thread: Thread[DefaultDispatcher-worker-2,5,main]
Dispatcher: Dispatchers.Main
but the next UI code definitely crashes.uli
03/29/2021, 7:30 AMlouiscad
03/29/2021, 7:30 AMDispatchers.Default
while the coroutineContext
has Dispatchers.Main
🤔svenjacobs
03/29/2021, 7:31 AMlouiscad
03/29/2021, 7:31 AMshowSnackbar()
, I'd wrap the body of the function itself with Dispatchers.Main { … }
svenjacobs
03/29/2021, 7:34 AMwithContext(Dispatchers.Main) { ... }
?louiscad
03/29/2021, 7:34 AMoperator fun invoke
for CoroutineDispatcher
.svenjacobs
03/29/2021, 7:42 AMlaunch
inherits the dispatcher...
It looked like this
launch(Dispatchers.Main) { someFunc() }
and in someFunc
...
launch { showSnackbar() }
...
However adding Dispatchers.Main
to the second launch
fixes this.uli
03/29/2021, 7:43 AMsvenjacobs
03/29/2021, 7:44 AMdelay
did not crash 🤷♂️🏼 Maybe just coincidence?uli
03/29/2021, 7:45 AMDispatchers.Main
while being on a default dispatcher’s thread?
Thread: Thread[DefaultDispatcher-worker-2,5,main]
Dispatcher: Dispatchers.Main
svenjacobs
03/29/2021, 7:45 AMlaunch
it now says
Thread[main,5,main]
uli
03/29/2021, 7:47 AMsvenjacobs
03/29/2021, 7:47 AMlaunch(Dispatchers.Main) {
launch { ... }
}
?louiscad
03/29/2021, 7:50 AM