https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sergio Crespo Toubes

08/27/2019, 6:24 AM
Copy code
private val uiJob = SupervisorJob()
val uiScope = CoroutineScope(Dispatchers.Main + uiJob)
val journeys = MutableLiveData<List<Journey>>()

fun loadJourneys() = uiScope.launch {
    val token = preferences.getProfileToken() ?: return@launch
    try {
        journeys.value = journeysService.getJourneys(token)
    }catch (e: Exception){
        showGenericError.value = Unit
    }
}
Hello i am trying coroutines with mvvm pattern. What i am doing bad with this? It´s working but the ui is blocked while is getting journeys. How can i fix this? Thanks.
g

gildor

08/27/2019, 6:43 AM
How
getJourneys
is implemented? If your UI is blocked, than getJourneys is blocking function
s

Sergio Crespo Toubes

08/27/2019, 6:44 AM
with suspend function
retrofit call
g

gildor

08/27/2019, 6:44 AM
Suspend function can be still blocking if implementation is not correct
s

Sergio Crespo Toubes

08/27/2019, 6:44 AM
yes i think so
g

gildor

08/27/2019, 6:44 AM
does it use standard retrofit suspend function support?
or it’s your own implementation?
s

Sergio Crespo Toubes

08/27/2019, 6:45 AM
Copy code
@GET("/api/me/journeys")
	suspend fun getJourneys(@Header(TOKEN) token: String): List<Journey>
g

gildor

08/27/2019, 6:46 AM
also:
Copy code
private val uiJob = SupervisorJob()
val uiScope = CoroutineScope(Dispatchers.Main + uiJob)
Can be replaced with:
val uiScope = MainScope()
Are you sure that you don’t have any nasty call adapters that may cause blocking? because it looks fine, nothing should be block. Also, could you check does it work if you replace
getJourneys()
with
delay(5000)
?
s

Sergio Crespo Toubes

08/27/2019, 6:47 AM
the problem of change MainScope to BackgroundScope is that i get an error assigning result of retrofit to mutablelivedata
for modifying ui thread in background thread
g

gildor

08/27/2019, 6:48 AM
yes
I understand
as I said, ecveryhing looks completely fine
s

Sergio Crespo Toubes

08/27/2019, 6:49 AM
ok...
g

gildor

08/27/2019, 6:49 AM
the problem of change MainScope to BackgroundScope
I do not suggesting this. Also
MainScope()
is just shortcut, it uses main dispatcher
s

Sergio Crespo Toubes

08/27/2019, 6:49 AM
the block that i am talking about is with viewpager when i change with gesture the view
the ui is blocked
I will try MainScope()
Thanks Andrey
g

gildor

08/27/2019, 6:50 AM
Nono, It’s not a solution
I just said that you can write the same shorter
s

Sergio Crespo Toubes

08/27/2019, 6:50 AM
ah XD ok
g

gildor

08/27/2019, 6:50 AM
also you can just get main scope from lifecycle/lifecycleObserver.coroutineScope
About your original problem, try replace
journeysService.getJourneys(token)
with placeholder like
delay(5000)
and check, will your UI is still blocking or not
s

Sergio Crespo Toubes

08/27/2019, 6:51 AM
ok
I will test it this evening Andrey, i cant now. Thanks for all.
4 Views