Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android Basics: Introduction to Coroutines in Android Studio #61

Open
ZanzibarNuclear opened this issue Dec 17, 2024 · 1 comment
Open

Comments

@ZanzibarNuclear
Copy link

I am on the starter branch. RaceTracker runs right away, and the Start/Pause button does not do anything.

@yuuk
Copy link

yuuk commented Dec 23, 2024

Here is my workaround

@Composable
fun RaceTrackerApp() {
    val playerOne = remember {
        RaceParticipant(name = "Player 1", progressIncrement = 1)
    }
    val playerTwo = remember {
        RaceParticipant(name = "Player 2", progressIncrement = 2)
    }
    var raceInProgress by remember { mutableStateOf(false) }

    val scope = rememberCoroutineScope()
    var playerOneTask by remember { mutableStateOf<Job?>(null) }
    var playerTwoTask by remember { mutableStateOf<Job?>(null) }

    // trigger button click event
    val onRunStateChange = { status: Boolean ->
        raceInProgress = status
        // start
        if (status) {
            scope.launch {
                coroutineScope {
                    playerOneTask = launch { playerOne.run() }
                    playerTwoTask = launch { playerTwo.run() }
                }
                raceInProgress = false
            }
        }
        // pause
        if (!status) {
            playerOneTask?.cancel()
            playerTwoTask?.cancel()
        }
    }

    RaceTrackerScreen(
        playerOne = playerOne,
        playerTwo = playerTwo,
        isRunning = raceInProgress,
        onRunStateChange = onRunStateChange,
        modifier = Modifier
            .statusBarsPadding()
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .safeDrawingPadding()
            .padding(horizontal = dimensionResource(R.dimen.padding_medium)),
    )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants