I'm calling launch inside a coroutinescope but it does not execute. Snackbar action listener is executing but the launch block is not executing for some reason.
CoroutineScope(Dispatchers.Main).launch {
val scope = this
val mn = snackbarManager(R.id.root)
Snackbar
.make(mn.container, R.string.recpt_deleted, Snackbar.LENGTH_LONG)
.setAction(R.string.undo) {
scope.launch { // not executing
Toast.makeText(requireContext(),"Committing",Toast.LENGTH_LONG).show()
Log.d("COMMIT", "calling commit")
}
}
.show()
}
The
scope
you are using in Snackbar action listener is not the same scope you use to call the firstlaunch
function. To tackle the problem you can make a reference to the mainCoroutineScope
:Or use another
CoroutineScope
in Snackbar action listener, for example,lifecycleScope
property:But in my opinion your code is a little bit mess. I think you should reconsider your approach and don't use the
CoroutineScope
to show theSnackbar
.UPDATE:
When you initialize
scope
variable in the first coroutineval scope = this
, thisscope
becomes COMPLETED when the outer coroutine is finished. When you launch inner coroutine inSnackbar
action listener thescope
already has COMPLETED state. We can't launch a coroutine usingCoroutineScope
with COMPLETED state.