user2399158
user2399158

Reputation: 591

How can I call jetpack compose function in Observable live data function?

Hi I try to call this a compose function from updatedata(it)

 viewModel.ResponseStatus.observe(viewLifecycleOwner) { status ->
                when (status) {
                    FragmentViewModel.PROCESSING,
                    FragmentViewModel.NOT_PROCESSING -> {
                        viewModel.object.let {
                            updatedata(it). <--- error?
                        } ?: faildialog()
                    }

This is how my updatadata() function

    @ExperimentalFoundationApi
    @OptIn(ExperimentalAnimationApi::class)
    @ExperimentalUnitApi
    @Composable
private fun updatedata(authdata: Payload) {
   composefunction(authdata.client_name)
}

The error I get is @Composable invocations can only happen from the context of a @Composable function

That is the compose function I am calling

 @ExperimentalUnitApi
    @ExperimentalAnimationApi
    @ExperimentalAnimationGraphicsApi
    @ExperimentalFoundationApi
    @Composable
    fun composefunction(name: String) {
      Box(){}
}

I am not familiar with flow or live data, much less on composable, which part I must change to get the live data to pass into the compose function?

Upvotes: 0

Views: 1639

Answers (1)

Mark Pazon
Mark Pazon

Reputation: 6205

In a Composable world, you don't tell the view what to do after a state changes.

@ExperimentalFoundationApi
@OptIn(ExperimentalAnimationApi::class)
@ExperimentalUnitApi
@Composable
private fun updatedata(viewModel: YourViewModel, authdata: Payload) {
   val responseState by viewModel.ResponseStatus.observeAsState()
    when (status) {
       FragmentViewModel.PROCESSING,
       FragmentViewModel.NOT_PROCESSING -> {
             viewModel.object.let {
                 composefunction(authdata.client_name)
             } ?: faildialog()
       }
    }
}

I highly encourage that you learn all the stuff you just mentioned: LiveData, MutableState and how to think in Composable as these things work together.

Upvotes: 2

Related Questions