Search code examples
androidkotlinandroid-jetpack-composeretrofit2

Problem with mutableStateFlow retrofit and jetpack compose


I use MutableStateFlow and get data from server i need username text on my screen In onCreate() i get profile method from viewModel and in log.d my data is correct, but textUserName not update in Composables if i use method 1 , and updated if i use method 2, but i need load data only once and use this in all app.

ViewModel class :


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 text

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

i try this and this work, but i want load data only once

 LaunchedEffect(key1 = Unit) { // i need without this, i want get data only once 
    viewModel.getProfile()
}

Solution

  • you can call getProfile() function inside init() method in your viewmodel class. ViewModel will not effect when Recomposition occur

    class Profile: ViewModel() {
       init(){
        getProfile()
       }
    }