Tugas Pertemuan ke-10 [Unscramble App]

Unscramble App - ViewModel dan State Management

Unscramble App - ViewModel dan State Management

Unscramble App adalah aplikasi Android word puzzle game yang dikembangkan menggunakan Jetpack Compose untuk mempelajari konsep ViewModel dan State Management. Aplikasi ini mengajarkan cara mengelola UI state, memisahkan business logic dari UI, dan mengimplementasikan architecture pattern yang baik dalam Android development.

ViewModel Implementation
class GameViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(GameUiState())
    val uiState: StateFlow<GameUiState> = _uiState.asStateFlow()

    private lateinit var currentWord: String
    private var usedWords: MutableSet<String> = mutableSetOf()

    init {
        resetGame()
    }

    fun resetGame() {
        usedWords.clear()
        _uiState.value = GameUiState(currentScrambledWord = pickRandomWordAndShuffle())
    }
}

🎯 ViewModel Pattern

ViewModel menyimpan dan mengelola UI state. MutableStateFlow digunakan untuk menyimpan state internal, sedangkan StateFlow yang read-only diekspos ke UI. ViewModel bertahan selama lifecycle activity/fragment.

State Management dengan StateFlow
data class GameUiState(
    val currentScrambledWord: String = "",
    val currentWordCount: Int = 1,
    val score: Int = 0,
    val isGuessWrong: Boolean = false,
    val isGameOver: Boolean = false
)

private fun updateGameState(updatedScore: Int) {
    if (usedWords.size == MAX_NO_OF_WORDS) {
        _uiState.value = _uiState.value.copy(
            isGuessWrong = false,
            score = updatedScore,
            isGameOver = true
        )
    } else {
        _uiState.value = _uiState.value.copy(
            isGuessWrong = false,
            currentScrambledWord = pickRandomWordAndShuffle(),
            currentWordCount = _uiState.value.currentWordCount.inc(),
            score = updatedScore
        )
    }
}

📊 State Data Class

GameUiState adalah immutable data class yang merepresentasikan seluruh UI state. Menggunakan copy() function untuk membuat state baru dengan perubahan spesifik, memastikan state consistency.

UI State Observation
@Composable
fun GameScreen(
    gameViewModel: GameViewModel = viewModel()
) {
    val gameUiState by gameViewModel.uiState.collectAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        GameLayout(
            currentScrambledWord = gameUiState.currentScrambledWord,
            wordCount = gameUiState.currentWordCount,
            score = gameUiState.score,
            isGuessWrong = gameUiState.isGuessWrong,
            onUserGuessChanged = { gameViewModel.updateUserGuess(it) },
            onKeyboardDone = { gameViewModel.checkUserGuess() }
        )
    }
}

🔄 State Collection

collectAsState() mengkonversi StateFlow menjadi Compose State. UI secara otomatis recompose ketika state berubah. ViewModel diperoleh menggunakan viewModel() delegate.

User Input Handling
fun updateUserGuess(guessedWord: String) {
    userGuess = guessedWord
}

fun checkUserGuess() {
    if (userGuess.equals(currentWord, ignoreCase = true)) {
        val updatedScore = _uiState.value.score.plus(SCORE_INCREASE)
        updateGameState(updatedScore)
    } else {
        _uiState.value = _uiState.value.copy(isGuessWrong = true)
    }
    updateUserGuess("")
}

fun skipWord() {
    updateGameState(_uiState.value.score)
    updateUserGuess("")
}

⌨️ Input Processing

Business logic untuk memproses user input disimpan di ViewModel. checkUserGuess() memvalidasi jawaban dan mengupdate score. skipWord() memungkinkan user melewati kata tanpa kehilangan score.

Game Features

Core Gameplay

  • Word scrambling algorithm
  • Score tracking system
  • Input validation
  • Game progression logic

State Management

  • Unidirectional data flow
  • Immutable state objects
  • Reactive UI updates
  • Lifecycle-aware components
Fungsi Utama ViewModel Code
  • 1. State Management
    ViewModel mengelola UI state menggunakan StateFlow, memastikan data consistency dan reactive updates.
  • 2. Business Logic Separation
    Logic game seperti scoring, validation, dan progression disimpan terpisah dari UI components.
  • 3. Configuration Changes
    ViewModel bertahan selama configuration changes, mempertahankan game state dan user progress.
Architecture Components
🏗️
ViewModel

Mengelola UI state dan business logic

🌊
StateFlow

Observable state holder untuk reactive UI

🎯
State

Immutable data class untuk UI state

🔄
Compose

Declarative UI yang reactive terhadap state

Kesimpulan: Unscramble App mendemonstrasikan implementasi clean architecture dengan ViewModel dan StateFlow. Pattern ini memisahkan concerns, meningkatkan testability, dan membuat aplikasi lebih maintainable dan scalable.
Tampilan Aplikasi
Unscramble App Light Mode
Dark Mode
Unscramble App Dark Mode
Light Mode
Video Demonstrasi
Source Code Repository

📂 Access Source Code

🔗 View on GitHub

Complete source code untuk Unscramble App dengan ViewModel dan State Management implementation

Comments

Popular Posts