Running coroutines function with withContext vs suspendCoroutine - android

I wish if you can elaborate about the difference when calling those 3 functions:
lifecycleScope.launch(Dispatchers.IO) {
var res = addTwoNumbers1(2,3)
}
lifecycleScope.launch {
withContext(Dispatchers.IO) {
var res = addTwoNumbers1(2, 3)
}
}
lifecycleScope.launch {
var res = addTwoNumbers2(2,3)
}
Functions:
suspend fun addTwoNumbers1(num1: Int, num2: Int): Int = suspendCoroutine { cont ->
val res = num1+num2
cont.resume(res)
}
suspend fun addTwoNumbers2(num1: Int, num2: Int) = withContext(Dispatchers.IO) {
val res = num1+num2
return#withContext res
}

First version launches a coroutine using Dispatcher.IO, meaning any code inside will execute on background thread, unless you change it
lifecycleScope.launch(Dispatchers.IO) {
var res = addTwoNumbers1(2,3) // This call executes on background thread (IO pool)
}
Second version launches a coroutine using Dispatchers.Main.immediate (UI thread, this is implicit for lifecycleScope)
lifecycleScope.launch { // Starts on UI thread
withContext(Dispatchers.IO) { // Here thread is changed to background (IO pool)
var res = addTwoNumbers1(2, 3)
}
}
Third one starts a new coroutine on UI thread and then calls a suspending function(doesn't actually suspend) which changes the Dispatcher to IO
lifecycleScope.launch { // Starts on UI thread
var res = addTwoNumbers2(2,3) // This function changes the dispatcher to IO
}
as for your suspending functions, addTwoNumbers1 is the only one that have the capability to suspend because it calls suspendCoroutine.
addTwoNumbers2 is not really a suspending function

Related

Switch from Main dispatcher to IO dispatcher from non lifecycle class

I m using coroutines in my android app, and i have this function that need to communicate with UI and Main thread.
private suspend fun init() : RequestProcessor<LocalData, ApiResult, ApiError>
{
#Suppress("LeakingThis")
_localData = listener.databaseCall()
withContext(Dispatchers.IO) {
if (_localData == null)
{
checkIfShouldFetch(null, null)
}
else
{
withContext(Dispatchers.Main) {
mediatorLiveData.addSource(_localData!!) { newLocalData ->
mediatorLiveData.removeSource(_localData!!)
// I want to call this from the IO thread.
checkIfShouldFetch(newLocalData, _localData)
}
}
}
}
return this
}
My question is, how to come back to the root context (IO) from the nested context (Main)?
when i call again withContext(Dispatchers.IO) this error is displayed : Suspension functions can be called only within coroutine body
I need to call the function checkIfShouldFetch(newLocalData, _localData) from the IO context and i didn't find how to do it.
You would need to launch a coroutine to call withContext in that place. What you can try to do without launching a coroutine is to use suspendCoroutine or suspendCancellableCoroutine to suspend execution until callback is fired:
withContext(Dispatchers.Main) {
val newLocalData = addSource()
checkIfShouldFetch(newLocalData, _localData)
}
suspend fun addSource(): LiveData<...> = suspendCoroutine { continuation ->
mediatorLiveData.addSource(_localData) { newLocalData ->
mediatorLiveData.removeSource(_localData)
continuation.resumeWith(newLocalData)
}
}
suspend fun checkIfShouldFetch(newLocalData: ..., _localData: ...) = withContext(Dispatchers.IO) {
// ...
}

How to wait for end of a coroutine

I have some code below. Delay (3000) is just replacement for a long loop (or cycle). I’m expecting that after completion of loop println(res) will print “Some String” and then enable button. But in real life println(res) prints an empty string and button became enabled at same time when I click it.
My question is: how I can wait for end of a coroutine and only after completion of the coroutine run println(res) and button.isEnabled = true.
private var res: String = ""
private suspend fun test(): String {
delay(3000) // delay - just replacement for long loop
return "Some String" // String received after loop
}
fun onClick(view: View) {
res = ""
button.isEnabled = false
GlobalScope.launch {
res = withContext(Dispatchers.Default) {
test()
}
}
println(res) // 1. trying to get string received after loop, but not working
button.isEnabled = true // 2. button must be enabled after loop in cycle, but it's not waiting till end of loop
}
The main thing to understand here is that code within coroutine is by default executed sequentially.
I.e. coroutine is executed asynchronously in relation to "sibling" code, but code within coroutine executes synchronously by default.
For example:
fun DoSometing () {
coroutineA {
doSomethingA1()
doSomethingA2()
}
some additional code
}
Corroutine A will execute async in relation to some additional code but doSometingA2 will be executed after doSomethingA1 is done.
That means, that within a coroutine every next piece of code will be executed after the previous one is done.
So, whatever you want to execute when coroutine is done, you just put at the end of that coroutine and declare context (withContext) in which you want to execute it.
The exception is of course if you start another async piece of code within coroutine (like another coroutine).
EDIT: If you need to update UI from the coroutine, you should execute that on the main context, i.e. you'll have something like this:
GlobalScope.launch (Dispatchers.IO) {
//do some background work
...
withContext (Dispatchers.Main) {
//update the UI
button.isEnabled=true
...
}
}
You can try some thing like this:
suspend fun saveInDb() {
val value = GlobalScope.async {
delay(1000)
println("thread running on [${Thread.currentThread().name}]")
10
}
println("value = ${value.await()} thread running on [${Thread.currentThread().name}]")
}
await will wait for the coroutine to finish and then run code below it
fun onClick(view: View) {
res = ""
button.isEnabled = false
GlobalScope.launch(Dispatchers.Main){ // launches coroutine in main thread
updateUi()
}
}
suspend fun updateUi(){
val value = GlobalScope.async { // creates worker thread
res = withContext(Dispatchers.Default) {
test()
}
}
println(value.await()) //waits for workerthread to finish
button.isEnabled = true //runs on ui thread as calling function is on Dispatchers.main
}
launch is for situations where you don't care about the result outside the coroutine. To retrieve the result of a coroutine use async.
val res = GlobalScope.async(Dispatchers.Default) { test() }.await()
Note: avoid using GlobalScope, provide your own CoroutineScope instead.
why you don't move println and button.isEnabled inside GlobalScope.launch coroutine.
fun onClick(view: View) {
res = ""
button.isEnabled = false
GlobalScope.launch {
val res = withContext(Dispatchers.Default) {
test()
}
println(res)
button.isEnabled = true
}
}
if you whant your code run on main thread add Dispatchers.Main as an argument.
GlobalScope.launch(Dispatchers.Main) {
val res = withContext(Dispatchers.Default) {
test()
}
println(res)
button.isEnabled = true
}
now println and button.isEnabled run on main thread and test() fun runs on Default which in real is a worker thread.
Use the Job.join(): Unit method to wait for a coroutine to finish before continuing with current the thread:
//launch coroutine
var result = ""
val request = launch {
delay(500)
result = "Hello, world!"
}
//join coroutine with current thread
request.join()
//print "Hello, world!"
println(result)

How to return ArrayList from Coroutine?

How to return ArrayList from Coroutine?
GlobalScope.launch {
val list = retrieveData(firstDateOfMonth,lastDateOfMonth)
}
suspend fun retrieveData(
first: Date,
last: Date,
): ArrayList<Readings> = suspendCoroutine { c ->
var sensorReadingsList : ArrayList<Readings>?=null
GlobalScope.launch(Dispatchers.Main) {
val task2 = async {
WebApi.ReadingsList(
activity,auth_token, first, last
)
}
val resp2 = task2.await()
if (resp2?.status == "Success") {
sensorReadingsList = resp2?.organization_sensor_readings
}
c.resume(sensorReadingsList)
}
}
Error
Type inference failed: Cannot infer type parameter T in inline fun
Continuation.resume(value: T): Unit None of the following
substitutions receiver:
Continuation? /* =
java.util.ArrayList? */> arguments:
(kotlin.collections.ArrayList? /* =
java.util.ArrayList? */)
I guess WebApi.ReadingsList is a non-suspending function. That means that you'll need to make a thread wait while it runs. You probably don't want to use Dispatchers.Main for that, since that would run it on the UI thread. Dispatchers.IO would be the normal choice.
You also really shouldn't call suspendCoroutine for this. That's meant for low-level interoperation with other kinds of async callbacks, which you don't have in this case. Something like this would be more appropriate:
suspend fun retrieveData(
first: Date,
last: Date,
): ArrayList<Readings>? {
val resp2 = withContext(Dispatchers.IO) {
WebApi.ReadingsList(activity,auth_token, first, last)
}
if (resp2?.status == "Success") {
return resp2?.organization_sensor_readings
}
return null
}
This will run the blocking call in a subordinate job on an IO thread. This ensures that if your coroutine is cancelled, then the subordinate job will be cancelled too -- although that won't interrupt the blocking call.

AsyncTask as kotlin coroutine

Typical use for AsyncTask: I want to run a task in another thread and after that task is done, I want to perform some operation in my UI thread, namely hiding a progress bar.
The task is to be started in TextureView.SurfaceTextureListener.onSurfaceTextureAvailable and after it finished I want to hide the progress bar. Doing this synchronously does not work because it would block the thread building the UI, leaving the screen black, not even showing the progress bar I want to hide afterwards.
So far I use this:
inner class MyTask : AsyncTask<ProgressBar, Void, ProgressBar>() {
override fun doInBackground(vararg params: ProgressBar?) : ProgressBar {
// do async
return params[0]!!
}
override fun onPostExecute(result: ProgressBar?) {
super.onPostExecute(result)
result?.visibility = View.GONE
}
}
But these classes are beyond ugly so I'd like to get rid of them.
I'd like to do this with kotlin coroutines. I've tried some variants but none of them seem to work. The one I would most likely suspect to work is this:
runBlocking {
// do async
}
progressBar.visibility = View.GONE
But this does not work properly. As I understand it, the runBlockingdoes not start a new thread, as AsyncTask would, which is what I need it to do. But using the thread coroutine, I don't see a reasonable way to get notified when it finished. Also, I can't put progressBar.visibility = View.GONE in a new thread either, because only the UI thread is allowed to make such operations.
I'm new to coroutines so I don't quite understand what I'm missing here.
To use a coroutine you need a couple of things:
Implement CoroutineScope interface.
References to Job and CoroutineContext instances.
Use suspend function modifier to suspend a coroutine without blocking the Main Thread when calling function that runs code in Background Thread.
Use withContext(Dispatchers.IO) function to run code in background thread and launch function to start a coroutine.
Usually I use a separate class for that, e.g. "Presenter" or "ViewModel":
class Presenter : CoroutineScope {
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job // to run code in Main(UI) Thread
// call this method to cancel a coroutine when you don't need it anymore,
// e.g. when user closes the screen
fun cancel() {
job.cancel()
}
fun execute() = launch {
onPreExecute()
val result = doInBackground() // runs in background thread without blocking the Main Thread
onPostExecute(result)
}
private suspend fun doInBackground(): String = withContext(Dispatchers.IO) { // to run code in Background Thread
// do async work
delay(1000) // simulate async work
return#withContext "SomeResult"
}
// Runs on the Main(UI) Thread
private fun onPreExecute() {
// show progress
}
// Runs on the Main(UI) Thread
private fun onPostExecute(result: String) {
// hide progress
}
}
With ViewModel the code is more concise using viewModelScope:
class MyViewModel : ViewModel() {
fun execute() = viewModelScope.launch {
onPreExecute()
val result = doInBackground() // runs in background thread without blocking the Main Thread
onPostExecute(result)
}
private suspend fun doInBackground(): String = withContext(Dispatchers.IO) { // to run code in Background Thread
// do async work
delay(1000) // simulate async work
return#withContext "SomeResult"
}
// Runs on the Main(UI) Thread
private fun onPreExecute() {
// show progress
}
// Runs on the Main(UI) Thread
private fun onPostExecute(result: String) {
// hide progress
}
}
To use viewModelScope add next line to dependencies of the app's build.gradle file:
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION"
At the time of writing final LIFECYCLE_VERSION = "2.3.0-alpha04"
Here is also implementation of Async Task using Kotlin coroutines and extension function on CoroutineScope.
Another approach is to create generic extension function on CoroutineScope:
fun <R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit,
doInBackground: () -> R,
onPostExecute: (R) -> Unit
) = launch {
onPreExecute()
val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
doInBackground()
}
onPostExecute(result)
}
Now we can use it with any CoroutineScope:
In ViewModel:
class MyViewModel : ViewModel() {
fun someFun() {
viewModelScope.executeAsyncTask(onPreExecute = {
// ...
}, doInBackground = {
// ...
"Result" // send data to "onPostExecute"
}, onPostExecute = {
// ... here "it" is a data returned from "doInBackground"
})
}
}
In Activity or Fragment:
lifecycleScope.executeAsyncTask(onPreExecute = {
// ...
}, doInBackground = {
// ...
"Result" // send data to "onPostExecute"
}, onPostExecute = {
// ... here "it" is a data returned from "doInBackground"
})
To use viewModelScope or lifecycleScope add next line(s) to dependencies of the app's build.gradle file:
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION" // for viewModelScope
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$LIFECYCLE_VERSION" // for lifecycleScope
At the time of writing final LIFECYCLE_VERSION = "2.3.0-alpha05".
You can get ProgressBar to run on the UI Main Thread, while using coroutine to run your task asynchronously.
Inside your override fun onCreate() method,
GlobalScope.launch(Dispatchers.Main) { // Coroutine Dispatcher confined to Main UI Thread
yourTask() // your task implementation
}
You can initialize,
private var jobStart: Job? = null
In Kotlin, var declaration means the property is mutable. If you
declare it as val, it is immutable, read-only & cannot be reassigned.
Outside the onCreate() method, yourTask() can be implemented as a suspending function, which does not block main caller thread.
When the function is suspended while waiting for the result to be returned, its running thread is unblocked for other functions to execute.
private suspend fun yourTask() = withContext(Dispatchers.Default){ // with a given coroutine context
jobStart = launch {
try{
// your task implementation
} catch (e: Exception) {
throw RuntimeException("To catch any exception thrown for yourTask", e)
}
}
}
For your progress bar, you can create a button to show the progress bar when the button is clicked.
buttonRecognize!!.setOnClickListener {
trackProgress(false)
}
Outside of onCreate(),
private fun trackProgress(isCompleted:Boolean) {
buttonRecognize?.isEnabled = isCompleted // ?. safe call
buttonRecognize!!.isEnabled // !! non-null asserted call
if(isCompleted) {
loading_progress_bar.visibility = View.GONE
} else {
loading_progress_bar.visibility = View.VISIBLE
}
}
An additional tip is to check that your coroutine is indeed running on
another thread, eg. DefaultDispatcher-worker-1,
Log.e("yourTask", "Running on thread ${Thread.currentThread().name}")
Hope this is helpful.
First, you have to run coroutine with launch(context), not with runBlocking:
https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html
Second, to get the effect of onPostExecute, you have to use
Activity.runOnUiThread(Runnable)
or View.post(Runnable).
This does not use coroutines, but it's a quick solution to have a task run in background and do something on UI after that.
I'm not sure about the pros and cons of this approach compared to the others, but it works and is super easy to understand:
Thread {
// do the async Stuff
runOnUIThread {
// do the UI stuff
}
// maybe do some more stuff
}.start()
With this solution, you can easily pass values and objects between the two entities. You can also nest this indefinitely.
The following approach might be able to suffice your needs. It requires less boilerplate code and works for 100% of usecases
GlobalScope.launch {
bitmap = BitmapFactory.decodeStream(url.openStream())
}.invokeOnCompletion {
createNotification()
}
private val TAG = MainActivity::class.simpleName.toString()
private var job = Job()
//coroutine Exception
val handler = CoroutineExceptionHandler { _, exception ->
Log.d(TAG, "$exception handled !")
}
//coroutine context
val coroutineContext: CoroutineContext get() = Dispatchers.Main + job + handler
//coroutine scope
private val coroutineScope = CoroutineScope(coroutineContext)
fun execute() = coroutineScope.launch {
onPreExecute()
val result = doInBackground() // runs in background thread without blocking the Main Thread
onPostExecute(result)
}
private suspend fun doInBackground(): String =
withContext(Dispatchers.IO) { // to run code in Background Thread
// do async work
//delay(5000) // simulate async work
loadFileFromStorage()
return#withContext "SomeResult"
}
// Runs on the Main(UI) Thread
private fun onPreExecute() {
LoadingScreen.displayLoadingWithText(this,"Loading Files",false)
}
// Runs on the Main(UI) Thread
private fun onPostExecute(result: String) {
//progressDialogDialog?.dismiss()
LoadingScreen.hideLoading()
// hide progress
}
I started migrating my AsyncTask stuff in my Android Project to using coroutines...and if you just really need to do something on the UI after completing the async task (i.e., you're just overriding doInBackGround and onPostExecute in AsyncTask)...something like this can be done (i tried this myself and it works):
val job = CoroutineScope(Dispatchers.IO).async {
val rc = ...
return#async rc
}
CoroutineScope(Dispatchers.Main).launch {
val job_rc = job.await() // whatever job returns is fed to job_rc
// do UI updates here
}
The job that you have doesn't need to use the I/O Dispatcher...you can just use the default if it's not I/O intensive.
however the the coroutine waiting for the job to complete needs to be in on the Main/UI thread so you can update UI.
Yes, there's some syntax sugar that can be used to make the above code look more cool but this is at least easier to grasp when one is just starting to migrate to using coroutines.

Kotlin Coroutines the right way in Android

I'm trying to update a list inside the adapter using async, I can see there is too much boilerplate.
Is it the right way to use Kotlin Coroutines?
can this be optimized more?
fun loadListOfMediaInAsync() = async(CommonPool) {
try {
//Long running task
adapter.listOfMediaItems.addAll(resources.getAllTracks())
runOnUiThread {
adapter.notifyDataSetChanged()
progress.dismiss()
}
} catch (e: Exception) {
e.printStackTrace()
runOnUiThread {progress.dismiss()}
} catch (o: OutOfMemoryError) {
o.printStackTrace()
runOnUiThread {progress.dismiss()}
}
}
After struggling with this question for days, I think the most simple and clear async-await pattern for Android activities using Kotlin is:
override fun onCreate(savedInstanceState: Bundle?) {
//...
loadDataAsync(); //"Fire-and-forget"
}
fun loadDataAsync() = async(UI) {
try {
//Turn on busy indicator.
val job = async(CommonPool) {
//We're on a background thread here.
//Execute blocking calls, such as retrofit call.execute().body() + caching.
}
job.await();
//We're back on the main thread here.
//Update UI controls such as RecyclerView adapter data.
}
catch (e: Exception) {
}
finally {
//Turn off busy indicator.
}
}
The only Gradle dependencies for coroutines are: kotlin-stdlib-jre7, kotlinx-coroutines-android.
Note: Use job.await() instead of job.join() because await() rethrows exceptions, but join() does not. If you use join() you will need to check job.isCompletedExceptionally after the job completes.
To start concurrent retrofit calls, you can do this:
val jobA = async(CommonPool) { /* Blocking call A */ };
val jobB = async(CommonPool) { /* Blocking call B */ };
jobA.await();
jobB.await();
Or:
val jobs = arrayListOf<Deferred<Unit>>();
jobs += async(CommonPool) { /* Blocking call A */ };
jobs += async(CommonPool) { /* Blocking call B */ };
jobs.forEach { it.await(); };
How to launch a coroutine
In the kotlinx.coroutines library you can start new coroutine using either launch or async function.
Conceptually, async is just like launch. It starts a separate coroutine which is a light-weight thread that works concurrently with all the other coroutines.
The difference is that launch returns a Job and does not carry any resulting value, while async returns a Deferred - a light-weight non-blocking future that represents a promise to provide a result later. You can use .await() on a deferred value to get its eventual result, but Deferred is also a Job, so you can cancel it if needed.
Coroutine context
In Android we usually use two context:
uiContext to dispatch execution onto the Android main UI thread (for the parent coroutine).
bgContext to dispatch execution in background thread (for the child coroutines).
Example
//dispatches execution onto the Android main UI thread
private val uiContext: CoroutineContext = UI
//represents a common pool of shared threads as the coroutine dispatcher
private val bgContext: CoroutineContext = CommonPool
In following example we are going to use CommonPool for bgContext which limit the number of threads running in parallel to the value of Runtime.getRuntime.availableProcessors()-1. So if the coroutine task is scheduled, but all cores are occupied, it will be queued.
You may want to consider using newFixedThreadPoolContext or your own implementation of cached thread pool.
launch + async (execute task)
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task = async(bgContext) { dataProvider.loadData("Task") }
val result = task.await() // non ui thread, suspend until finished
view.showData(result) // ui thread
}
launch + async + async (execute two tasks sequentially)
Note: task1 and task2 are executed sequentially.
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
// non ui thread, suspend until task is finished
val result1 = async(bgContext) { dataProvider.loadData("Task 1") }.await()
// non ui thread, suspend until task is finished
val result2 = async(bgContext) { dataProvider.loadData("Task 2") }.await()
val result = "$result1 $result2" // ui thread
view.showData(result) // ui thread
}
launch + async + async (execute two tasks parallel)
Note: task1 and task2 are executed in parallel.
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task1 = async(bgContext) { dataProvider.loadData("Task 1") }
val task2 = async(bgContext) { dataProvider.loadData("Task 2") }
val result = "${task1.await()} ${task2.await()}" // non ui thread, suspend until finished
view.showData(result) // ui thread
}
How to cancel a coroutine
The function loadData returns a Job object which may be cancelled. When the parent coroutine is cancelled, all its children are recursively cancelled, too.
If the stopPresenting function was called while dataProvider.loadData was still in progress, the function view.showData will never be called.
var job: Job? = null
fun startPresenting() {
job = loadData()
}
fun stopPresenting() {
job?.cancel()
}
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task = async(bgContext) { dataProvider.loadData("Task") }
val result = task.await() // non ui thread, suspend until finished
view.showData(result) // ui thread
}
The complete answer is available in my article Android Coroutine Recipes
I think you can get rid of runOnUiThread { ... } by using UI context for Android applications instead of CommonPool.
The UI context is provided by the kotlinx-coroutines-android module.
We also have another option. if we use Anko library , then it looks like this
doAsync {
// Call all operation related to network or other ui blocking operations here.
uiThread {
// perform all ui related operation here
}
}
Add dependency for Anko in your app gradle like this.
implementation "org.jetbrains.anko:anko:0.10.5"
Like sdeff said, if you use the UI context, the code inside that coroutine will run on UI thread by default. And, if you need to run an instruction on another thread you can use run(CommonPool) {}
Furthermore, if you don't need to return nothing from the method, you can use the function launch(UI) instead of async(UI) (the former will return a Job and the latter a Deferred<Unit>).
An example could be:
fun loadListOfMediaInAsync() = launch(UI) {
try {
withContext(CommonPool) { //The coroutine is suspended until run() ends
adapter.listOfMediaItems.addAll(resources.getAllTracks())
}
adapter.notifyDataSetChanged()
} catch(e: Exception) {
e.printStackTrace()
} catch(o: OutOfMemoryError) {
o.printStackTrace()
} finally {
progress.dismiss()
}
}
If you need more help I recommend you to read the main guide of kotlinx.coroutines and, in addition, the guide of coroutines + UI
If you want to return some thing from background thread use async
launch(UI) {
val result = async(CommonPool) {
//do long running operation
}.await()
//do stuff on UI thread
view.setText(result)
}
If background thread is not returning anything
launch(UI) {
launch(CommonPool) {
//do long running operation
}.await()
//do stuff on UI thread
}
All the above answers are right, but I was having a hard time finding the right import for the UI from kotlinx.coroutines, it was conflicting with UI from Anko.
Its
import kotlinx.coroutines.experimental.android.UI
Here's the right way to use Kotlin Coroutines. Coroutine scope simply suspends the current coroutine until all child coroutines have finished their execution. This example explicitly shows us how child coroutine works within parent coroutine.
An example with explanations:
fun main() = blockingMethod { // coroutine scope
launch {
delay(2000L) // suspends the current coroutine for 2 seconds
println("Tasks from some blockingMethod")
}
coroutineScope { // creates a new coroutine scope
launch {
delay(3000L) // suspends this coroutine for 3 seconds
println("Task from nested launch")
}
delay(1000L)
println("Task from coroutine scope") // this line will be printed before nested launch
}
println("Coroutine scope is over") // but this line isn't printed until nested launch completes
}
Hope this helps.
Please find attached the implementation for a remote API call with Kotlin Coroutines & Retrofit library.
import android.view.View
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.test.nyt_most_viewed.NYTApp
import com.test.nyt_most_viewed.data.local.PreferenceHelper
import com.test.nyt_most_viewed.data.model.NytAPI
import com.test.nyt_most_viewed.data.model.response.reviews.ResultsItem
import kotlinx.coroutines.*
import javax.inject.Inject
class MoviesReviewViewModel #Inject constructor(
private val nytAPI: NytAPI,
private val nytApp: NYTApp,
appPreference: PreferenceHelper
) : ViewModel() {
val moviesReviewsResponse: MutableLiveData<List<ResultsItem>> = MutableLiveData()
val message: MutableLiveData<String> = MutableLiveData()
val loaderProgressVisibility: MutableLiveData<Int> = MutableLiveData()
val coroutineJobs = mutableListOf<Job>()
override fun onCleared() {
super.onCleared()
coroutineJobs.forEach {
it.cancel()
}
}
// You will call this method from your activity/Fragment
fun getMoviesReviewWithCoroutine() {
viewModelScope.launch(Dispatchers.Main + handler) {
// Update your UI
showLoadingUI()
val deferredResult = async(Dispatchers.IO) {
return#async nytAPI.getMoviesReviewWithCoroutine("full-time")
}
val moviesReviewsResponse = deferredResult.await()
this#MoviesReviewViewModel.moviesReviewsResponse.value = moviesReviewsResponse.results
// Update your UI
resetLoadingUI()
}
}
val handler = CoroutineExceptionHandler { _, exception ->
onMoviesReviewFailure(exception)
}
/*Handle failure case*/
private fun onMoviesReviewFailure(throwable: Throwable) {
resetLoadingUI()
Log.d("MOVIES-REVIEWS-ERROR", throwable.toString())
}
private fun showLoadingUI() {
setLoaderVisibility(View.VISIBLE)
setMessage(STATES.INITIALIZED)
}
private fun resetLoadingUI() {
setMessage(STATES.DONE)
setLoaderVisibility(View.GONE)
}
private fun setMessage(states: STATES) {
message.value = states.name
}
private fun setLoaderVisibility(visibility: Int) {
loaderProgressVisibility.value = visibility
}
enum class STATES {
INITIALIZED,
DONE
}
}

Categories

Resources