shuffle questions list

This commit is contained in:
Mylloon 2024-01-04 16:49:46 +01:00
parent 9156ad9776
commit 7f2ca7f022
Signed by: Anri
GPG key ID: A82D63DFF8D1317F
2 changed files with 10 additions and 13 deletions

View file

@ -31,7 +31,7 @@ fun PlayScreen(
idSet: Int, idSet: Int,
model: PlayViewModel = viewModel() model: PlayViewModel = viewModel()
) { ) {
// First update the list // First update the list of questions
model.updateQuestionList(idSet) model.updateQuestionList(idSet)
val question by model.currentQuestion val question by model.currentQuestion

View file

@ -7,12 +7,11 @@ import androidx.lifecycle.viewModelScope
import fr.uparis.diamantkennel.memorisationapplication.MemoApplication import fr.uparis.diamantkennel.memorisationapplication.MemoApplication
import fr.uparis.diamantkennel.memorisationapplication.data.Question import fr.uparis.diamantkennel.memorisationapplication.data.Question
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
class PlayViewModel(application: Application) : AndroidViewModel(application) { class PlayViewModel(application: Application) : AndroidViewModel(application) {
private val dao = (application as MemoApplication).database.memoDao() private val dao = (application as MemoApplication).database.memoDao()
private lateinit var questions: Flow<List<Question>> private lateinit var questions: List<Question>
var currentQuestion = mutableStateOf<Question?>(null) var currentQuestion = mutableStateOf<Question?>(null)
private var index = mutableStateOf(0) private var index = mutableStateOf(0)
@ -26,22 +25,20 @@ class PlayViewModel(application: Application) : AndroidViewModel(application) {
fun updateQuestionList(setId: Int) { fun updateQuestionList(setId: Int) {
if (currentQuestion.value == null) { if (currentQuestion.value == null) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
questions = dao.loadQuestions(setId) dao.loadQuestions(setId).collect { questionList ->
updateQuestion() questions = questionList.shuffled()
updateQuestion()
}
} }
} }
} }
private fun updateQuestion() { private fun updateQuestion() {
viewModelScope.launch { if (index.value >= questions.size) {
questions.collect { questionList -> /* Fin des questions */
if (index.value >= questionList.size) { index.value = 0
/* Fin des questions */
index.value = 0
}
currentQuestion.value = questionList[index.value]
}
} }
currentQuestion.value = questions[index.value]
} }
private fun reset() { private fun reset() {