https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lukas Lechner

08/04/2020, 9:14 AM
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

Desmond Teo

08/04/2020, 9:19 AM
there can be use cases for ui programming, check out https://medium.com/androiddevelopers/suspending-over-views-19de9ebd7020
👍 1
e

Erik

08/04/2020, 9:19 AM
I've seen examples of UI animations being handled in
lifecycleScope
g

Giorgos Neokleous

08/04/2020, 9:21 AM
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

flosch

08/04/2020, 9:32 AM
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

dekans

08/04/2020, 2:12 PM
Most when you want to handle UI events, like clicks. Or do actions from UI callbacks (e.g.
onPrepareMenu
)
3 Views