git.iko.soy/opencode-android
on bc6b45e help sign in
59 lines 2.4 kB history raw
1package soy.iko.opencode.ui.file
3import androidx.compose.runtime.Immutable
4import androidx.lifecycle.ViewModel
5import androidx.lifecycle.viewModelScope
6import soy.iko.opencode.data.model.FileContent
7import soy.iko.opencode.di.AppContainer
8import soy.iko.opencode.R
9import kotlinx.coroutines.ExperimentalCoroutinesApi
10import kotlinx.coroutines.flow.MutableStateFlow
11import kotlinx.coroutines.flow.StateFlow
12import kotlinx.coroutines.flow.asStateFlow
13import kotlinx.coroutines.flow.collectLatest
14import kotlinx.coroutines.flow.merge
15import kotlinx.coroutines.launch
16import soy.iko.opencode.util.runCatchingCancellable
18@Immutable
19data class FileViewState(
20 val loading: Boolean = true,
21 val content: FileContent? = null,
22 val error: String? = null,
25@OptIn(ExperimentalCoroutinesApi::class)
26class FileViewModel(
27 private val container: AppContainer,
28 private val path: String,
29) : ViewModel() {
31 private val _state = MutableStateFlow(FileViewState())
32 val state: StateFlow<FileViewState> = _state.asStateFlow()
34 /** Incremented by [reload] to trigger a fresh fetch without waiting for a connection change. */
35 private val _reload = MutableStateFlow(0)
37 fun reload() { _reload.value++ }
39 init {
40 // Observe the active connection so the file loads (or reloads) when a connection
41 // becomes available — including when the view opens during a reconnect window
42 // where activeConnection.value was momentarily null. collectLatest cancels the
43 // in-flight load if the connection is replaced mid-read. The reload trigger is
44 // merged in so a manual retry (e.g. after a transient error) re-fetches.
45 viewModelScope.launch {
46 merge(container.activeConnection, _reload).collectLatest {
47 val conn = container.activeConnection.value
48 if (conn == null) {
49 _state.value = FileViewState(loading = false, error = container.string(R.string.not_connected))
50 return@collectLatest
51 }
52 _state.value = FileViewState(loading = true)
53 runCatchingCancellable { conn.api.readFile(path) }
54 .onSuccess { _state.value = FileViewState(loading = false, content = it) }
55 .onFailure { _state.value = FileViewState(loading = false, error = container.friendlyError(it)) }
56 }
57 }
58 }