gildor / kotlin-coroutines-retrofit

Kotlin Coroutines await() extension for Retrofit Call
Apache License 2.0
847 stars 64 forks source link

No Response When Call a Service #28

Closed MohamedTaher closed 7 years ago

MohamedTaher commented 7 years ago

I use awaitResult method

public fun asyncCreateNewTask(dayPlanTask: DayPlanTask) = runBlocking {
        var state: Status = Status.Error

        val service = InspectionAPI().getInspectionService()

        val result : Result<Reply.Single<DayPlanTask>> = service.createWeeklyPlanTask(dayPlanTask).awaitResult()
        when (result) {
            is Result.Ok -> {
                state = Status.OK
            }
            is Result.Error -> {
                state = Status.InternalServerError
            }
            is Result.Exception -> {
                state = Status.Error
            }
            else -> {
                Log.e("WAIT_TRY", "ELSE branch")
            }
        }

        Log.e("STATE", state.toString())
    }

the app is stuck and not responsible, also it's not throwing any exception it isn't entered in onResponse and onFailure functions at CallAwait.awaitResult()

gildor commented 7 years ago

the app is stuck and not responsible

runBlocking blocks the thread and should be used only when it's fine for you, but it's definitely wrong for UI thread. Replace it with launch(DispatcherOnYourChoice) where DispatcherOnYourChoice can be UI (if you want to touch views inside your coroutine) or any other dispatcher, depending on your case.

also it's not throwing any exception

I don't see a case when your code could throw an exception. Could you please explain your problem.

Please read Guide to UI programming with coroutines

gildor commented 7 years ago

@MohamedTaher I just realized that my examples could be confusing for people who never used coroutines, so I added a note about runBlocking to Readme

MohamedTaher commented 7 years ago

Now I use launch(UI) instead of runBlocking and It's working well Thanks a lot