Home > Enterprise >  How to avoid call observe() twice?
How to avoid call observe() twice?

Time:10-30

I have an observer inside a function. I call this function firstly in my activity's onCreate() and it works fine. After that when I call this function again, the code inside my observer is called twice. How can I prevent this behaviour?

Here is my function with observer

private lateinit var word: String

fun addViews() {

    viewModel.getQuestion()

    viewModel.questionResponse.observe(this, { it ->
        this.word = it.data.word

            createAnswerTextView(this.word.length)

        }
    })
}

CodePudding user response:

You have to define your observer in "onViewCreated" if you are working in a fragment, or in your onCreateView if you are working in an activity.

Also, in your fragment you should define your viewmodel as:

val yourviewModel by activityViewModels<YourViewModel>()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        yourviewModel.yourVariable.observe(viewLifecycleOwner) {
          // some function to do
        }
}

And in your activity as:

val yourviewModel by viewModels<YourViewModel>()

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        yourviewModel.yourVariable.observe(this) {
          // some function to do
        }
}

If you don't want to do this, there is another way and it is just to remove all the observers:

fun addViews() {

    viewModel.getQuestion()

    // add this line
    viewModel.questionResponse.removeObservers(this)
    viewModel.questionResponse.observe(this, { it ->
        this.word = it.data.word

            createAnswerTextView(this.word.length)

        }
    })
}

CodePudding user response:

always call an observer inside onCreate in activity. You are registering your observer every-time you call addViews() function. Just move below code to inside onCreate

viewModel.questionResponse.observe(this, { it ->
        this.word = it.data.word

            createAnswerTextView(this.word.length)

        }
    })
  • Related