1

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

SayantanRC
  • 799
  • 7
  • 23
  • 1
    You could start with a codelab: https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#0 – Traendy Jan 16 '20 at 10:08
  • 1
    Please, don't go off on people because their English isn't perfect, especially when they are trying hard to be polite. What is preventing them is that they don't know how to proceed. Duh. This is a case where a useful link could be very helpful. (The codelabs helps you understand coroutines, but doesn't help in translating an AsyncTask to coroutines; that is not part of their tutorial.) – SMBiggs Oct 29 '20 at 21:22
  • please refer to this answer https://stackoverflow.com/a/62542551/1731626 – Sergio Apr 02 '22 at 10:58

1 Answers1

0

I suggest that you use work manager instead of service, you can use Coroutine Worker and add all your work there and you can use the method setForground(notification) to show notification from the worker, see the blog in medium. I hope i've answered your question

https://medium.com/androiddevelopers/workmanager-meets-kotlin-b9ad02f7405e

Fahad Alotaibi
  • 416
  • 3
  • 9