Skip to content

Instantly share code, notes, and snippets.

@ShinichiroFunatsu
Last active November 1, 2019 08:57
Show Gist options
  • Save ShinichiroFunatsu/561d2001fc83a1b0daa12b2169ed07e0 to your computer and use it in GitHub Desktop.
Save ShinichiroFunatsu/561d2001fc83a1b0daa12b2169ed07e0 to your computer and use it in GitHub Desktop.
JetpackCompose And Counter! ! Easy Sample!
class CounterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
val countStatus = +state { 0 }
val liveCount = MutableLiveData<Int>().apply {
value = 0
this.observe(this@MainActivity, Observer{ inc ->
countStatus.value = inc
})
}
val isRunCountup = MutableLiveData<Boolean>().apply {
value = false
}
var countInt = 0
val countupLoop = {
Thread {
while (true) {
if (isRunCountup.value!!) liveCount.postValue(countInt++)
else return@Thread
Thread.sleep(1)
}
}.start()
}
run.observe(this@MainActivity, Observer {
if (it) countupLoop()
})
Column {
Padding(40.dp) {
Text("Count:${countStatus.value}", style = TextStyle(fontSize = 20.sp))
}
Padding(40.dp) {
Ripple(bounded = true) {
Button(onClick = { isRunCountup.toggle() }, text = "toggle")
}
}
}
}
}
}
}
fun MutableLiveData<Boolean>.toggle() = apply { value = !value!! }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment