Skip to content

Instantly share code, notes, and snippets.

@igorescodro
Created March 29, 2021 18:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorescodro/c1188f7c2dd0ee15e28d38759ec3f0bd to your computer and use it in GitHub Desktop.
Save igorescodro/c1188f7c2dd0ee15e28d38759ec3f0bd to your computer and use it in GitHub Desktop.
@Composable
fun HomeList(taskViewModel: ListViewModel = viewModel()) {
val coroutineScope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
val onShowSnackbar: (Task) -> Unit = { task ->
coroutineScope.launch {
val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
message = "${task.title} completed",
actionLabel = "Undo"
)
when (snackbarResult) {
SnackbarResult.Dismissed -> Timber.d("Snackbar dismissed")
SnackbarResult.ActionPerformed -> taskViewModel.onCheckedChange(task)
}
}
}
Scaffold(
scaffoldState = scaffoldState,
topBar = { HomeTopBar() }
) {
val list by remember(taskViewModel) { taskViewModel.taskList }.collectAsState()
LazyColumn {
items(
items = list,
key = { it.id },
itemContent = { task ->
ListItem(
task = task,
onCheckedChange = { task ->
taskViewModel.onCheckedChange(task)
onShowSnackbar(task)
}
)
}
)
}
}
}
@Composable
private fun ListItem(task: Task, onCheckedChange: (Task) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(64.dp)
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = task.isCompleted,
onCheckedChange = { onCheckedChange(task) }
)
Spacer(Modifier.width(8.dp))
Text(
text = task.title,
style = MaterialTheme.typography.body1,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
}
}
@Composable
private fun HomeTopBar() {
TopAppBar {
Box(modifier = Modifier.fillMaxSize()) {
Text(
modifier = Modifier.align(Alignment.Center),
style = MaterialTheme.typography.h5,
text = "My tasks"
)
}
}
}
data class Task(val id: Long, val title: String, var isCompleted: Boolean)
class ListViewModel : ViewModel() {
private val list = mutableListOf(
Task(1L, "Buy milk", false),
Task(2L, "Watch 'Call Me By Your Name'", false),
Task(3L, "Listen 'Local Natives'", false),
Task(4L, "Study about 'fakes instead of mocks'", false),
Task(5L, "Congratulate Rafael", false),
Task(6L, "Watch Kotlin YouTube Channel", false)
)
private val _taskList: MutableStateFlow<List<Task>> = MutableStateFlow(list)
val taskList: StateFlow<List<Task>>
get() = _taskList.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), listOf())
fun onCheckedChange(task: Task) {
list.find { it.id == task.id }?.isCompleted = task.isCompleted.not()
_taskList.value = list.filter { it.isCompleted.not() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment