I am new to coroutines. This is a general question. I have looked into other questions, but they are more specific to a particular use case.
Currently, I am using the following callback based architecture:
class MyService: Service(), OnComplete {
...
companion object {
lateinit var serviceContext: Context
}
...
override fun onCreate() {
super.onCreate()
serviceContext = this
}
...
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
MyAsyncTask().execute() // start the background job
return super.onStartCommand(intent, flags, startId)
}
...
override fun onCompleteFunc(resultBundle: Bundle) {
// do something when the job is finished
}
}
The AsyncTask is as follows:
class MyAsyncTask: AsyncTask<Any, Any, Any>() {
...
val onComplete by lazy { MyService.serviceContext as OnComplete }
...
override fun doInBackground(vararg params: Any?): Any {
// do the background job here
// store the results somewhere
return 0
}
...
override fun onPostExecute(result: Any?) {
super.onPostExecute(result)
onComplete.onCompleteFunc( // job finished. send the results
Bundle().apply {
// put extras here
}
)
}
}
And the interface:
interface OnComplete {
fun onCompleteFunc(resultBundle: Bundle)
}
I am very much interested in moving to kotlin coroutines. Kindly help me with this.
Regards, Sayantan