Asynchronous Tasks using Kotlin Coroutines

Asked

Viewed 22 times

0

I’m readjusting an application and need to implement asynchronous routines using the coroutines. I am currently trying to use the function 'Globalscope.Launch(Dispatchers.Main) {}' as an alternative to runOnUiThread {}' to update my views.

My question is whether this approach is the right one for this type of situation and whether there is another way to do it using the coroutines but without using Globalscope.

BEFORE:

override fun onEvent(event: EventModel) {

    runOnUiThread {
        eventList.add(event)
        val tamanho = eventList.size

        if(tamanho > 0){
            adapterType.postData(eventList)
            adapterChannel.postData(eventList)
            adapterMessage.postData(eventList)
        }
    }

}

NOW:

    override fun onEvent(event: EventModel) {

        GlobalScope.launch(Dispatchers.Main) {
            eventList.add(event)
            val tamanho = eventList.size

            if(tamanho > 0){
                adapterType.postData(eventList)
                adapterChannel.postData(eventList)
                adapterMessage.postData(eventList)
            }   
        }

    }

Briefly, this function receives data from a websocket and updates a recycleview every time it receives a new event.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.