5

I'm trying out coroutines instead of RxJava on basic network calls for the fist time to see what it's like and running into some issues with lag/threading

In the below code, I'm doing a network call userRepo.Login() and if an exception happens I show an error message and stop the progress animation that I started at the start of the function.

If I leave everything on the CommonPool (or don't add any pool) it crashes saying the animation must be done on a looper thread if an exception happens. In other circumstances I've received errors saying this must be done on the UI thread as well, same problem, different thread requirements.

I can't launch the whole coroutine on the UI thread though, because the login call will block since it's on the UI thread and messes up my animation (which makes sense).

The only way I can see to resolve this, is the launch a new coroutine on the UI thread from within the existing coroutine, which works, but seems weird.

Is this the proper way to do things, or am I missing something?

override fun loginButtonPressed(email: String, password: String) {

    view.showSignInProgressAnimation()

    launch(CommonPool) {
        try { 
            val user = userRepo.login(email, password)

            if (user != null) {
                view.launchMainActivity()
            }

        } catch (exception: AuthException) {
            launch(UI) {
                view.showErrorMessage(exception.message, exception.code)
                view.stopSignInProgressAnimation()
            }
        }
    }
}

1 Answer 1

11

You should start from the opposite end: launch a UI-based coroutine, from which you hand off heavy operations to an external pool. The tool of choice is withContext():

override fun loginButtonPressed(email: String, password: String) {
    view.showSignInProgressAnimation()
    // assuming `this` is a CoroutineScope with dispatcher = Main...
    this.launch {
        try {
            val user = withContext(IO) { 
                userRepo.login(email, password) 
            }
            if (user != null) {
                view.launchMainActivity()
            }
        } catch (exception: AuthException) {
            view.showErrorMessage(exception.message, exception.code)
            view.stopSignInProgressAnimation()
        }
    }
}

This way you keep your natural Android programming model, which assumes the GUI thread.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.