Skip to content

Instantly share code, notes, and snippets.

@y2k
Last active June 3, 2023 21:05
Show Gist options
  • Save y2k/47d452e983f41ea2c12386fac025f75d to your computer and use it in GitHub Desktop.
Save y2k/47d452e983f41ea2c12386fac025f75d to your computer and use it in GitHub Desktop.
Effector - Kotlin - TodoList
val addClicked = Event.create<Unit>()
val textChanged = Event.create<String>()
val itemDeleted = Event.create<Int>()
private val itemAdded = Event.create<String>()
val storeText = Store.create("")
.on(textChanged) { _, newText -> newText }
.reset(itemAdded)
val storeAddEnabled = storeText.map { it.isNotEmpty() }
val storeItems = Store.create(emptyList<String>())
.on(itemAdded) { items, newItem -> items + newItem }
.on(itemDeleted) { items, position -> items.filterIndexed { i, _ -> i != position } }
fun main() {
sample(
clock = addClicked,
source = storeText,
target = itemAdded,
)
}
@Composable
fun TodoList() {
Column(
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(4.dp),
horizontalAlignment = Alignment.End,
) {
TextField(
modifier = Modifier.fillMaxWidth(),
value = storeText.get(),
onValueChange = { textChanged(it) }
)
Button(
enabled = storeAddEnabled.get(),
onClick = { addClicked(Unit) }) {
Text(text = "Add")
}
Column(modifier = Modifier.fillMaxWidth()) {
for ((i, item) in storeItems.get().withIndex()) {
Row {
Text(
modifier = Modifier
.weight(1f)
.padding(vertical = 8.dp),
text = item
)
Button(onClick = { itemDeleted(i) }) { Text(text = "Delete") }
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment