1. What is a coroutine?
1-1 How it different from a Thread?
- Executed inside of a thread.
- Suspendable
- Can easily change their context (the thread they're running in)
2. Launch a coroutine
2-1 Global scope
- Live as long as the application does. Will be destroyed after the execution is done.
|
|
2-2. Suspend function
- A suspend function can only be called in another suspend function or inside of a coroutine.
- Use
withContext
to switch to another thread
|
|
- Use
runBlocking
to start a coroutine in the main thread- Different from using
GlobalScope.launch(Dispatchers.main)
, which won't block the main thread whereas runBlocking will. - Use cases
- Want to simply call suspend function from the main thread but don't care about the UI behavior
- Call suspend function in junit test
- debug a coroutine (set logs before and after the execution)
- Different from using
|
|
2-3. Jobs, Waiting, Cancellation
- Launch a coroutine will actually return a
Job
- Use
Job.cancel()
to cancel a job.
|
|
Equivalent to:
|
|
2-4. Async and Await
- functions inside of a coroutine are executed synchronously by default
|
|
- async function will get a
Deferred
result of type String(in this case) - await function will block the coroutine until the result is returned
- use
measureTimeMillis{ }
to measure the duration of time
|
|
2-5. lifecycleScope & viewModelScope
- Add dependencies
|
|
- lifecycleScope
- Make a coroutine stick with the current Activity/Fragment's lifecycle. Ensure the coroutine is destroyed if the holder is destroyed.
- viewModelScope
- Make a coroutine stick with the current viewModel lifecycle.