https://kotlinlang.org logo
#android
Title
# android
i

Ive Vasiljevic

05/10/2019, 6:15 PM
How to handle Login request with coroutines and retrofit. I have a problem where I make async request and await in my repo and in viewmodel I call that suspend function with coroutine scope and launch builder, but in my view (fragment) the next line is "evaluatestatuscode" so that function is called without waiting for request to finish. Do I need another Coroutine in my view too? My question is how can I get to request status code. So when I get 200 I transfer to next screen and when I get 401 I display a message.
r

rook

05/10/2019, 6:24 PM
Post your code
g

gergo

05/10/2019, 6:33 PM
if you expect that in the next line you have the status, i think what you want to do is launch{ val response = startRequest(); process(response); } where startRequest is a suspend function which calls the retrofit call and awaits it. But without code this is guessing.
i

Ive Vasiljevic

05/10/2019, 6:33 PM
I hope you can figure what I'm saying
g

gergo

05/10/2019, 6:39 PM
well that's the expected behaviour, launch returns immediately. if you want to do the evaluation you should do it inside your launch lambda after the request call.
i

Ive Vasiljevic

05/10/2019, 6:45 PM
So I can use some kind of middleware (utility class) that takes care of that evaluation that acts as a bridge between my view and viewmodel.
r

rook

05/10/2019, 7:30 PM
Evaluate just needs to be called within
launch
You have a lot of layers of indirection, perhaps a couple too many. I adjusted your code to compensate for that. https://pastebin.com/3i1zTF7X
g

gergo

05/10/2019, 7:57 PM
well, i am not sure about ur architecture, but if u use viewmodel i suppose its mvvm. in that case the evaluation should happen inside the viewmodel, and the viewmodel should expose an observable field (state) which represents the result of the request after evaluation. on ur view u should observe this observable and update the ui accordingly. does this makes sense to u?
12 Views