Advertisement
loloof64

Simple Jetpack Compose project : Game viewmodel

Dec 22nd, 2022
1,170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.34 KB | Gaming | 0 0
  1. package com.loloof64.compose_chess_experiment.ui.screens.game
  2.  
  3. import androidx.lifecycle.ViewModel
  4. import androidx.lifecycle.viewModelScope
  5. import com.loloof64.compose_chess_experiment.data.repositories.ChessGame
  6. import com.loloof64.compose_chess_experiment.data.repositories.ChessGameRepository
  7. import dagger.hilt.android.lifecycle.HiltViewModel
  8. import kotlinx.coroutines.Dispatchers
  9. import kotlinx.coroutines.flow.SharingStarted
  10. import kotlinx.coroutines.flow.StateFlow
  11. import kotlinx.coroutines.flow.map
  12. import kotlinx.coroutines.flow.stateIn
  13. import kotlinx.coroutines.launch
  14. import javax.inject.Inject
  15.  
  16. data class ChessGameUiState(
  17.     val currentPosition: String,
  18. )
  19.  
  20. @HiltViewModel
  21. class ChessGameViewModel @Inject constructor(
  22.     private val gameRepository: ChessGameRepository
  23. ) : ViewModel() {
  24.     val uiState : StateFlow<ChessGameUiState> = gameRepository.game.map {
  25.         return@map ChessGameUiState(currentPosition = it.currentPosition)
  26.     }.stateIn(
  27.         initialValue = ChessGameUiState(currentPosition = ChessGame.emptyPosition),
  28.         scope = viewModelScope,
  29.         started = SharingStarted.WhileSubscribed(5000)
  30.     )
  31.  
  32.     fun newGame(startPosition: String = ChessGame.defaultPosition) {
  33.         viewModelScope.launch(Dispatchers.Default) {
  34.             gameRepository.newGame(startPosition)
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement