Saltar al contenido
Snippets·Gratis

Snippets de Kotlin y Android

20 snippets de Kotlin para apps Android: estado de UI sellado, un ViewModel de Hilt con StateFlow, corrutinas, entidades y DAO de Room, y estado y listas de Compose. Escribe un prefijo como uistate o hiltvm en un archivo .kt.

Se instala gratis.

Si tienes PocketCode instalado en tu Android, esto abre la página en la app.

Vista previa

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

Cambios en la 1.0.0

Primera versión.

Relacionados