Created
October 11, 2020 11:31
-
-
Save t-artikov/1422b5a26ca82973578bb6cbd5eaa7ad to your computer and use it in GitHub Desktop.
Jetpack Compose counter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.compose | |
import android.os.Bundle | |
import androidx.appcompat.app.AppCompatActivity | |
import androidx.compose.foundation.Text | |
import androidx.compose.foundation.clickable | |
import androidx.compose.foundation.layout.Column | |
import androidx.compose.material.Button | |
import androidx.compose.material.MaterialTheme | |
import androidx.compose.runtime.* | |
import androidx.compose.runtime.snapshots.snapshotFlow | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.platform.setContent | |
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.flow.launchIn | |
import kotlinx.coroutines.flow.onEach | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
MaterialTheme() { | |
Counters() | |
} | |
} | |
} | |
} | |
class CountersModel(scope: CoroutineScope) { | |
var appleCount by mutableStateOf(0) | |
private set | |
var orangeCount by mutableStateOf(0) | |
private set | |
val total by derivedStateOf { appleCount + orangeCount } | |
init { | |
snapshotFlow { "Total: $total" } | |
.onEach(::println) | |
.launchIn(scope) | |
} | |
fun incApples() { | |
appleCount++ | |
} | |
fun incOranges() { | |
orangeCount++ | |
} | |
fun reset() { | |
appleCount = 0 | |
orangeCount = 0 | |
} | |
} | |
@Composable | |
fun Counters() { | |
val scope = rememberCoroutineScope() | |
val model = remember { CountersModel(scope) } | |
Column { | |
Text( | |
"Apples: ${model.appleCount}", | |
modifier = Modifier.clickable(onClick = model::incApples) | |
) | |
Text( | |
"Oranges: ${model.orangeCount}", | |
modifier = Modifier.clickable(onClick = model::incOranges) | |
) | |
Text("Total: ${model.total}") | |
Button(onClick = model::reset) { | |
Text("Reset") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment