Skip to content

Instantly share code, notes, and snippets.

@Composable
fun MviQuestionDestination(
mviViewModel: MviViewModel,
onConfirm: () -> Unit
) {
val textFieldState = remember { mutableStateOf(TextFieldValue()) }
val viewState = mviViewModel.viewState.collectAsState()
val onConfirmClicked = { mviViewModel.onAction(MviViewModel.UiAction.AnswerConfirmed(textFieldState.value.text)) }
class MvvmViewModel(
private val answerService: AnswerService,
) {
private val coroutineScope = MainScope()
private val _isLoading: MutableStateFlow<Boolean> = MutableStateFlow(false)
val isLoading = _isLoading.asStateFlow()
private val _textToDisplay: MutableStateFlow<String> = MutableStateFlow("")
@Composable
fun MvvmQuestionDestination(
mvvmViewModel: MvvmViewModel,
onConfirm: () -> Unit
) {
val textFieldState = remember { mutableStateOf(TextFieldValue()) }
// We only want the event stream to be attached once
// even if there are multiple re-compositions
LaunchedEffect("key") { // probably is a better way to set the key than hardcoding key...
@Composable
fun MvvmApp(
mvvmViewModel: MvvmViewModel
) {
val navController = rememberNavController()
NavHost(navController, startDestination = "question") {
composable("question") {
MvvmQuestionDestination(
mvvmViewModel = mvvmViewModel,
// You could pass the nav controller to further composables,
class MvvmActivity : AppCompatActivity() {
private val mvvmViewModel = MvvmViewModel(AnswerService())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeListPlaygroundTheme {
MvvmApp(mvvmViewModel)
}
@enyciaa
enyciaa / compose-architecture-2
Created February 23, 2021 21:18
compose-architecture-2
val answerService = remember { AnswerService() }
val textToDisplay = remember {
if (isCorrect) {
"You've heard too many cheese jokes"
} else {
"Nacho cheese"
}
}
@enyciaa
enyciaa / compose-architecture-0
Last active February 28, 2021 22:20
compose-architecture-0
class AnswerService {
suspend fun save(answer: String) {
Log.v("Api call", "Make a call to an api")
delay(1000)
}
}
@enyciaa
enyciaa / compose-architecture-1
Created February 23, 2021 20:57
compose-architecture-1
@Composable
fun HomeScreen() {
Column {
Text("Hello World!")
}
}
@Composable
fun TodoItem(
modifier: Modifier,
todo: Todo,
onTodoChecked: (todo: Todo, isChecked: Boolean) -> Unit,
) {
Card(modifier = modifier, elevation = 8.dp) {
Row(modifier = Modifier.padding(8.dp)) {
Text(text = todo.title)
Spacer(modifier = Modifier.weight(1f))
class TodoViewModel {
private val todoRepository = TodoRepository()
private val viewStatePublisher: MutableStateFlow<ViewState> = MutableStateFlow(initViewState())
private val lastViewState: ViewState
get() = viewStatePublisher.value
private fun initViewState(): ViewState {
val todos = todoRepository.fetchTodos()
return ViewState(todoList = todos)