Are there any good use cases for launching corouti...
# coroutines
l
Are there any good use cases for launching coroutines in activities / fragments in the
lifecycleScope
? IMO most (all?) coroutines should be started in
viewModelScope
because then they continue to run on orientation changes.
d
there can be use cases for ui programming, check out https://medium.com/androiddevelopers/suspending-over-views-19de9ebd7020
👍 1
e
I've seen examples of UI animations being handled in
lifecycleScope
g
You can expose a flow or channel (including StateFlow) from your presenter/viewmodel which then you can observe on
lifecycleScope
, it will act similarly to livedata. This with a combination of the
launchWhenXXXX
extensions
4
f
Or wrap a permission request in a
suspendCancellableCoroutine
and launch it in the lifecycleScope
Copy code
suspend fun Fragment.suspendingPermissionRequest(
    permission: String
): Boolean = suspendCancellableCoroutine<Boolean> { continuation ->
    val requestPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { result ->
        continuation.resume(result)
    }
    requestPermission.launch(permission)
    continuation.invokeOnCancellation { requestPermission.unregister() }
}

class SomeFragment : Fragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            val granted = suspendingPermissionRequest(WRITE_EXTERNAL_STORAGE)
        }
    }
}
👍 1
🙂 1
d
Most when you want to handle UI events, like clicks. Or do actions from UI callbacks (e.g.
onPrepareMenu
)