跳转至

Kotlin 模式

此文件使用 Kotlin 以及 Android/KMP 特定内容扩展 common/patterns.md。

依赖注入

优先使用构造函数注入。使用 Koin(KMP)或 Hilt(仅 Android):

// Koin — モジュール宣言
val dataModule = module {
    single<ItemRepository> { ItemRepositoryImpl(get(), get()) }
    factory { GetItemsUseCase(get()) }
    viewModelOf(::ItemListViewModel)
}

// Hilt — アノテーション
@HiltViewModel
class ItemListViewModel @Inject constructor(
    private val getItems: GetItemsUseCase
) : ViewModel()

ViewModel 模式

单一状态对象、事件接收器、单向数据流:

data class ScreenState(
    val items: List<Item> = emptyList(),
    val isLoading: Boolean = false
)

class ScreenViewModel(private val useCase: GetItemsUseCase) : ViewModel() {
    private val _state = MutableStateFlow(ScreenState())
    val state = _state.asStateFlow()

    fun onEvent(event: ScreenEvent) {
        when (event) {
            is ScreenEvent.Load -> load()
            is ScreenEvent.Delete -> delete(event.id)
        }
    }
}

仓库模式

  • suspend 函数返回 Result<T> 或自定义错误类型
  • 响应式流使用 Flow
  • 协调本地和远程数据源
interface ItemRepository {
    suspend fun getById(id: String): Result<Item>
    suspend fun getAll(): Result<List<Item>>
    fun observeAll(): Flow<List<Item>>
}

UseCase 模式

单一职责、operator fun invoke:

class GetItemUseCase(private val repository: ItemRepository) {
    suspend operator fun invoke(id: String): Result<Item> {
        return repository.getById(id)
    }
}

class GetItemsUseCase(private val repository: ItemRepository) {
    suspend operator fun invoke(): Result<List<Item>> {
        return repository.getAll()
    }
}

expect/actual(KMP)

用于平台特定实现:

// commonMain
expect fun platformName(): String
expect class SecureStorage {
    fun save(key: String, value: String)
    fun get(key: String): String?
}

// androidMain
actual fun platformName(): String = "Android"
actual class SecureStorage {
    actual fun save(key: String, value: String) { /* EncryptedSharedPreferences */ }
    actual fun get(key: String): String? = null /* ... */
}

// iosMain
actual fun platformName(): String = "iOS"
actual class SecureStorage {
    actual fun save(key: String, value: String) { /* Keychain */ }
    actual fun get(key: String): String? = null /* ... */
}

协程模式

  • 在 ViewModel 中使用 viewModelScope,对结构化子作业使用 coroutineScope
  • 将冷 Flow 转换为 StateFlow 时使用 stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue)
  • 需要隔离子协程失败时使用 supervisorScope

使用 DSL 的 Builder 模式

class HttpClientConfig {
    var baseUrl: String = ""
    var timeout: Long = 30_000
    private val interceptors = mutableListOf<Interceptor>()

    fun interceptor(block: () -> Interceptor) {
        interceptors.add(block())
    }
}

fun httpClient(block: HttpClientConfig.() -> Unit): HttpClient {
    val config = HttpClientConfig().apply(block)
    return HttpClient(config)
}

// 使用例
val client = httpClient {
    baseUrl = "https://api.example.com"
    timeout = 15_000
    interceptor { AuthInterceptor(tokenProvider) }
}

参考

技能:kotlin-coroutines-flows 中可参考详细的协程模式。 技能:android-clean-architecture 中可参考模块和分层模式。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC