我使用 MutableStateFlow 并从服务器获取数据,我需要屏幕上的用户名文本 在 onCreate() 中,我从 viewModel 获取配置文件方法,在 log.d 中,我的数据是正确的,但如果我使用方法 1 ,则 textUserName 不会在可组合项中更新,如果我使用方法 2 则更新,但我只需要加载数据一次并使用它在所有应用程序中。
ViewModel 类:
private val _getProfileResponseStateFlow: MutableStateFlow<ProfileResponse> =
MutableStateFlow(ProfileResponse())
val getProfileResponseStateFlow = _getProfileResponseStateFlow.asStateFlow()
fun getProfile() {
viewModelScope.launch {
val result = getProfileUseCase.execute(
sharedPreferences.getAccessToken()?.toBearer().toString()
)
if (result.isSuccessful) {
isSuccessGetProfile.value = true
_getProfileResponseStateFlow.value = result.body()!!
}
}
}
可组合文本
@Composable
fun UserName(
modifier: Modifier,
fontSize: TextUnit
) {
val viewModel: MainViewModel = hiltViewModel()
val profileDataState by viewModel.getProfileResponseStateFlow.collectAsState()
Text(
text = profileDataState.name.toString(),
modifier = modifier,
fontWeight = FontWeight.Normal,
fontSize = fontSize,
color = MaterialTheme.colorScheme.primary
)
}
我尝试了这个和这个工作,但我只想加载数据一次
LaunchedEffect(key1 = Unit) { // i need without this, i want get data only once
viewModel.getProfile()
}
您可以在视图模型类中的
getProfile()
方法中调用 init()
函数。发生重组时 ViewModel 将不起作用
class Profile: ViewModel() {
init(){
getProfile()
}
}