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
scopeyou are using in Snackbar action listener is not the same scope you use to call the firstlaunchfunction. To tackle the problem you can make a reference to the mainCoroutineScope:Or use another
CoroutineScopein Snackbar action listener, for example,lifecycleScopeproperty:But in my opinion your code is a little bit mess. I think you should reconsider your approach and don't use the
CoroutineScopeto show theSnackbar.UPDATE:
When you initialize
scopevariable in the first coroutineval scope = this, thisscopebecomes COMPLETED when the outer coroutine is finished. When you launch inner coroutine inSnackbaraction listener thescopealready has COMPLETED state. We can't launch a coroutine usingCoroutineScopewith COMPLETED state.