代码片段·免费
Kotlin 与 Android 代码片段
20 个面向 Android 应用的 Kotlin 代码片段:密封 UI 状态、带 StateFlow 的 Hilt ViewModel、协程、Room 实体与 DAO,以及 Compose 状态和列表。在 .kt 文件中输入 uistate 或 hiltvm 等前缀即可。
免费安装。
如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。
预览
20 个中的 5 个
Sealed UI stateuistate
Loading, success and error states for a screen
sealed interface ${1:Ui}State {
data object Loading : ${1:Ui}State
data class Success(val ${2:data}: ${3:String}) : ${1:Ui}State
data class Error(val message: String) : ${1:Ui}State
}Hilt ViewModel with StateFlowhiltvm
ViewModel with an injected repository and a read-only state
@HiltViewModel
class ${1:Feature}ViewModel @Inject constructor(
private val ${2:repository}: ${3:Repository},
) : ViewModel() {
private val _state = MutableStateFlow(${1:Feature}UiState())
val state: StateFlow<${1:Feature}UiState> = _state.asStateFlow()
fun ${4:load}() {
viewModelScope.launch {
$0
}
}
}Update StateFlow statestupd
Change a field of the state with update and copy
_state.update { it.copy(${1:isLoading = true}) }Collect state in Composecollectst
Read a StateFlow in a composable, aware of the lifecycle
val ${1:state} by ${2:viewModel}.${3:state}.collectAsStateWithLifecycle()Switch to the IO dispatcherwithio
Suspend function that runs blocking work off the main thread
suspend fun ${1:loadData}(): ${2:String} = withContext(Dispatchers.IO) {
${3:TODO()}
}1.0.0 的变更
首个版本。