Search code examples
kotlinkotlinx.coroutines

How to acces view properties from coroutines result


I am trying to do simple request to backend with coroutines

    uiScope.launch {
        try {
             result = URL("https://httpbin.org/get").readText()
            text.text = result
        } catch (error: Error) {
            text.text = error.message
        } finally {
                log(this@MainActivity,result)

        }
    }

but this exeption is thrown:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

How to solve it?


Solution

  • I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's LiveDate value which subsequently will chane the UI

        var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
        viewModel.selected.observe(this, Observer{ users ->
    
            text.text = users
        })
        uiScope.launch {
                try {
                    result = URL("http://jsonplaceholder.typicode.com/posts").readText()
                    viewModel.selected.postValue(result)
                } catch (error: Error) {
                    viewModel.selected.postValue(error.toString())
                }
    
        }
        log(this@MainActivity,result)