Pular para o conteúdo
Snippets·Grátis

Snippets de Kotlin e Android

20 snippets de Kotlin para apps Android: estado de UI selado, um ViewModel do Hilt com StateFlow, corrotinas, entidades e DAOs do Room, e estado e listas do Compose. Digite um prefixo como uistate ou hiltvm em um arquivo .kt.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

5 de 20

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()}
}

Mudanças na 1.0.0

Primeira versão.

Relacionados