kotlin-android
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKotlin Android Skill
Kotlin Android 技能
Production-ready Android development with Jetpack libraries.
基于Jetpack库的可用于生产环境的Android开发。
Topics Covered
涵盖主题
MVVM Pattern
MVVM模式
kotlin
@HiltViewModel
class UserViewModel @Inject constructor(
private val repository: UserRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState = _uiState.asStateFlow()
fun load() = viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
repository.getUsers()
.onSuccess { users -> _uiState.update { it.copy(users = users, isLoading = false) } }
}
}kotlin
@HiltViewModel
class UserViewModel @Inject constructor(
private val repository: UserRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState = _uiState.asStateFlow()
fun load() = viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
repository.getUsers()
.onSuccess { users -> _uiState.update { it.copy(users = users, isLoading = false) } }
}
}Compose UI
Compose UI
kotlin
@Composable
fun UserScreen(viewModel: UserViewModel = hiltViewModel()) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
UserContent(state)
}kotlin
@Composable
fun UserScreen(viewModel: UserViewModel = hiltViewModel()) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
UserContent(state)
}Type-Safe Navigation
类型安全导航
kotlin
@Serializable
data class ProfileRoute(val userId: String)
composable<ProfileRoute> { entry ->
val route: ProfileRoute = entry.toRoute()
}kotlin
@Serializable
data class ProfileRoute(val userId: String)
composable<ProfileRoute> { entry ->
val route: ProfileRoute = entry.toRoute()
}Troubleshooting
问题排查
| Issue | Resolution |
|---|---|
| Recomposition loop | Mark class @Stable or use derivedStateOf |
| ViewModel recreated | Use hiltViewModel() not viewModel() |
| 问题 | 解决方法 |
|---|---|
| 重组循环 | 为类添加@Stable注解或使用derivedStateOf |
| ViewModel被重建 | 使用hiltViewModel()而非viewModel() |
Usage
使用方法
Skill("kotlin-android")Skill("kotlin-android")