Home > Software engineering >  Observer scope can't use global variable
Observer scope can't use global variable

Time:10-06

private var Name = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModelFactory = MainViewModelFactory(repository)
    viewModel = ViewModelProvider(this,viewModelFactory).get(MainViewModel::class.java)
    // viewmodel data

    setContent {
        SimpleStockInfoTheme {
            viewModel.getData().observe(this, Observer {
                Name.add(it)
                Log.d("EROR", Name.toString())
            })
            Log.d("EROR2", Name.toString())
                InfoCard(name = "dad", data = 1442.32 )


        }
    }

In Observer scope, global variable Name(mutableList) have a value (it). but outside of that, Name is empty List.. Why this situation happended??

CodePudding user response:

In Observer scope, global variable Name(mutableList) have a value (it). but outside of that, Name is empty List

Name list is empty outside of the observer block because of the execution order of the statements.

Log statement outside of the observer executes first, then the Log statement inside of the observer blog gets executed. What happens here is, all Live Data observers get registered first, and when the execution of synchronous code gets completed, after the execution of observer code starts.

This goes for suspending functions too, they would only start executing after all synchronous code execution completes

Once it is added to the Name in the observer block, accessing Name after that won't return an empty list.

  • Related