Yokan / rebuild
Course 1 8624561

LocalLibraryBrowseViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryBrowseViewModel.kt

implementation51 lines
1package eu.friedcutlet.yokan.ui.screens.local23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import kotlinx.coroutines.CoroutineDispatcher6import kotlinx.coroutines.Dispatchers7import eu.friedcutlet.yokan.domain.ItemType8import eu.friedcutlet.yokan.domain.Manga9import eu.friedcutlet.yokan.services.catchingNonCancellation10import eu.friedcutlet.yokan.services.library.LocalLibraryController11import kotlinx.coroutines.flow.MutableStateFlow12import kotlinx.coroutines.flow.StateFlow13import kotlinx.coroutines.flow.asStateFlow14import kotlinx.coroutines.flow.update15import kotlinx.coroutines.launch1617data class LocalLibraryBrowseUiState(18    /** Every local-archive title per type, sorted by name. */19    val titlesByType: Map<ItemType, List<Manga>> = emptyMap(),20    val scanMessage: String? = null,21    val scanning: Boolean = false,22)2324class LocalLibraryBrowseViewModel(25    private val controller: LocalLibraryController,26    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,27) : ViewModel() {28    private val _state = MutableStateFlow(LocalLibraryBrowseUiState())29    val state: StateFlow<LocalLibraryBrowseUiState> = _state.asStateFlow()3031    init {32        viewModelScope.launch {33            controller.observeLibrary(workDispatcher).collect { library ->34                _state.update { it.copy(titlesByType = library.browseTitlesByType) }35            }36        }37    }3839    fun rescan() {40        if (_state.value.scanning) return41        _state.update { it.copy(scanning = true) }42        viewModelScope.launch {43            val result = catchingNonCancellation { controller.rescan() }44            val message = result.fold(45                onSuccess = { "Last scan: ${it.total} items, ${it.added} added, ${it.updated} updated" },46                onFailure = { error -> "Scan failed: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" },47            )48            _state.update { it.copy(scanMessage = message, scanning = false) }49        }50    }51}52

Search chapters, reference and source filenames.