0

After update androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1' a got error Method addObserver must be called on the main thread.This error i got then i try to use:

viewLifecycleOwner.lifecycleScope.launch {
                        val userId = withContext(Dispatchers.IO) {
                            viewModel.login(
                                    username.text.toString()
                            )
                        }

                        when {

As i fount information i need to call it on mainThread, but if i do it (i use Dispatchers.Main), i got another error. Please help me that im doging wrong. Before upate everything work fine.

fXs
  • 1
  • 1

1 Answers1

0

I think was wrong about the problem. Lets start from beginning. I have application on SdkVersion 23. I got new device and i start using BroadcastReceiver(). But after that i got error about Room database, i found information that i have to update Room dependencies, so that i done, after the one dependencies i have to update another and another and so on....So in this end i have to change SdkVersion 30. And then begin problems. Right now application start but when i try to send request to server to get information i got error. If i connect to server like was in SdkVersion 23:

Code in LoginFragment:
            viewLifecycleOwner.lifecycleScope.launch {
                val userId = withContext(Dispatchers.IO) {
                    viewModel.login(
                            username.text.toString(),
                            password.text.toString(),
                            url.text.toString(),
                            database.text.toString()
                    )
                }

I got error : Method addObserver must be called on the main thread. As i unterstand it said me that i have to do in mainThred. So okey i try in Main Thred like this(Just delete Dispatchers.IO):

>                       viewLifecycleOwner.lifecycleScope.launch {
>                         viewModel.login(
>                                 username.text.toString(),
>                                 password.text.toString(),
>                                 url.text.toString(),
>                                 database.text.toString()
>                         )
>                     }
> 
>                     when {

Then i got error that i cant to connection to server in main thread. If i understand correctly AsyncTask was deprecated in API level 30(How can I fix 'android.os.NetworkOnMainThreadException'?) so i cant no longer use withContext(Dispatchers.IO) method or what? I dont understant how i have to connect to server to get information in SdkVersion 30 in best and correct way in Kotlin? Or i am wrong about situation?

fXs
  • 1
  • 1