git.iko.soy/opencode-android
on e37d1bb help sign in
39 lines 1.5 kB history raw
1package soy.iko.opencode.di
3import android.content.Context
4import soy.iko.opencode.data.model.ServerProfile
5import soy.iko.opencode.data.repo.ProfileStore
6import soy.iko.opencode.data.repo.SettingsStore
7import kotlinx.coroutines.CoroutineScope
8import kotlinx.coroutines.Dispatchers
9import kotlinx.coroutines.SupervisorJob
10import kotlinx.coroutines.flow.MutableStateFlow
11import kotlinx.coroutines.flow.StateFlow
12import kotlinx.coroutines.flow.asStateFlow
14/**
15 * Hand-written service locator held by [soy.iko.opencode.OpencodeApp]. Owns the
16 * process-wide singletons and the currently active [OpencodeConnection].
17 */
18class AppContainer(context: Context) {
20 val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
21 val profileStore = ProfileStore(context)
22 val settingsStore = SettingsStore(context)
24 private val _activeConnection = MutableStateFlow<OpencodeConnection?>(null)
25 val activeConnection: StateFlow<OpencodeConnection?> = _activeConnection.asStateFlow()
27 /** Open (or re-open) a connection to [profile], replacing any current one. */
28 suspend fun connect(profile: ServerProfile): OpencodeConnection {
29 disconnect()
30 val resolved = profileStore.resolve(profile).copy(lastUsed = System.currentTimeMillis())
31 profileStore.save(resolved)
32 return OpencodeConnection(resolved).also { _activeConnection.value = it }
33 }
35 fun disconnect() {
36 _activeConnection.value?.close()
37 _activeConnection.value = null
38 }