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

carbaj0

01/19/2023, 6:38 PM
Should I pass the CoroutineScope or should I make the functions suspend?
👌 2
Copy code
data class Login(
    val back: suspend () -> Unit,
    val next: suspend () -> Unit,
    val name: String,
    val onChange: (String) -> Unit,
    override val route: String = "Login",
) : Screen

context(Navigator, Reducer, SearchRepository)
fun Login(): Login =
    Login(
        next = { LoginPassword().navigate() },
        back = { back() },
        name = "name",
        onChange = { reducer<Login> { copy(name = it) } }
    )

fun main() {
    val scope = CoroutineScope(Job())
    val store = Store()
    val repo = SearchRepository()

    with(store, scope, repo) {
        state<Login> {
           scope.launch { next() }
        }
    }
}
vs
Copy code
data class Login(
    val back: () -> Unit,
    val next: () -> Unit,
    val name: String,
    val onChange: (String) -> Unit,
    override val route: String = "Login",
) : Screen

context(Navigator, Reducer, SearchRepository, CoroutineScope)
fun Login(): Login =
    Login(
        next = { LoginPassword().navigate() },
        back = { launch { back() } },
        name = "name",
        onChange = { reducer<Login> { copy(name = it) } }
    )

fun main() {
    val scope = CoroutineScope(Job())
    val store = Store(scope)
    val repo = SearchRepository()

    with(store, scope, repo) {
        state<Login> {
            next() 
        }
    }
}
c

Casey Brooks

01/19/2023, 6:48 PM
The difference between passing the
CoroutineScope
and using
suspend
are not meant to be interchangeable, they communicate different things about how that function is used.
suspend
should be used when you intend that function to be one step of a sequence of async steps, because it will suspend until the computation has completed. passing the
CoroutineScope
communicates that the function will be running in parallel to everything else. It’s tied to the same coroutine cancellation, but will not suspend and will return immediately so other work can be started, while anything
launched
into that scope from within the function will continue to run in the background. So
suspend
is intended for treating async code sequentially just like regular code. coroutineScope is for fire-and-forget tasks
c

carbaj0

01/19/2023, 7:14 PM
Since this represents a screen’s state, it could make sense to pass the CoroutineScope, since I don’t want to depend on it being launched by an Activity, a Fragment, or Compose.
k

Kevin Del Castillo

01/19/2023, 7:15 PM
@Casey Brooks I wouldn't use the term "fire-and-forget" tasks with
CoroutineScope
, you could always return a
Job
if you see convenient to do so in case you ever want to cancel the launched job, or do something else with it.
5 Views