0

I am writing an RSS Feed app in kotlin, and I got it working, but I want to write this AsyncTask code using Kotlin coroutines. How can I write this code using Kotlin coroutines?

    class RssFeedFetcher(val context: RSSFragment) : AsyncTask<URL, Void, List<RssItem>>() {

    private val reference = WeakReference(context)
    private var stream: InputStream? = null;
    override fun doInBackground(vararg params: URL?): List<RssItem>? {
        val connect = params[0]?.openConnection() as HttpURLConnection

        connect.readTimeout = 8000
        connect.connectTimeout = 8000
        connect.requestMethod = "GET"
        connect.connect();
        val responseCode: Int = connect.responseCode;
        var rssItems: List<RssItem>? = null
        if (responseCode == 200) {
            stream = connect.inputStream;

            try {
                val parser = RssParser()
                rssItems = parser.parse(stream!!)

            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return rssItems
    }

    override fun onPostExecute(result: List<RssItem>?) {
        super.onPostExecute(result)
        if (result != null && result.isNotEmpty()) {
            reference.get()?.updateRV(result)
        }
    }
Stack Fox
  • 1,201
  • 9
  • 14
  • It's helpful but I'm not quite sure how can I write this specific code as a coroutine – Stack Fox Apr 27 '20 at 09:03
  • 1
    Use [this answer](https://stackoverflow.com/a/58900195/115145). Put your `doInBackground()` logic in that answer's `doSomeBackgroundWork()` function. Put your `onPostExecute()` logic in that answer's `doUiStuff()` function. – CommonsWare Apr 27 '20 at 10:40

0 Answers0