A
A
Al2019-03-13 15:50:36
Android
Al, 2019-03-13 15:50:36

How can code be optimized with coroutines?

The question may seem stupid. I recently started learning coroutines, but still.
Let's say we have a class like this:

class MainActivity : AppCompatActivity(), CoroutineScope {

    private var job: Job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        launch {
            var user: UserData? = service.doLogin("test", "1111")
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }

}

The doLogin method looks like this:
suspend fun doLogin(login: String, pass: String): UserData? {
        return try {
            service.logIn(login, pass).await()
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

This all works as it should, but the question is: is it possible to somehow write code so that the service.doLogin() call does not need to be wrapped in launch?
Those. similar to how it would work in javascript (syntactic example):
async onCreate(savedInstanceState: Bundle?) {
    var user: UserData? = await service.doLogin("test", "1111")
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

After all, we can’t write like this: override suspend fun onCreate.
Maybe there is some way to write an @launch() annotation that would execute the onCreate code in the CoroutineScope. Or is this all a stupid idea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tiberal, 2019-03-13
@Tiberal

You can think of suspend as a breakpoint in a coroutine. Accordingly, suspend methods are called only in coroutines (launch, async, runBlocking, actor). You cannot delegate sdk methods like suspend , because they are called inside the framework where no one knows about your coroutines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question