Answer the question
In order to leave comments, you need to log in
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()
}
}
suspend fun doLogin(login: String, pass: String): UserData? {
return try {
service.logIn(login, pass).await()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
async onCreate(savedInstanceState: Bundle?) {
var user: UserData? = await service.doLogin("test", "1111")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question