1

My app splash screen is use to fetch data from network and after data fetch is success, I want to send user to Home screen. Usually, we use Thread.sleep or Handler to stay on Splash screen for some time. Can we do this using suspend function of Kotlin?

2 Answers2

1

Use Anko, it is simple and clear, and your owner is JetBrains

Step 1. Getting anko

Put it on your app/build.gradle

dependencies {
    ...
    implementation "org.jetbrains.anko:anko:0.10.5"
    ...
}

Step 2. Using anko

Inside of your SplashActivity, on your onCreate() try as follow

doAsync {
    val result = URL("your request here").readText()
    //depending of your result go to MainActivity
}

See more about Anko here

Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
  • 1
    Can we solve it using kotlin co-routine library(experimental)? Using suspend function on network call. – Pratik Burkhawala Jul 16 '18 at 17:47
  • How about without anko? – JPM Oct 31 '18 at 16:23
  • @JPM, you can use `AsyncTask`, see more [here](https://stackoverflow.com/a/14251115/6733404) – Abner Escócio Oct 31 '18 at 16:29
  • I'd rather stick with the future and use coroutines, we are not using anko right now so need a solution for just coroutines. I've been looking at a few but the library keeps changing and all the solutions out there are old. – JPM Oct 31 '18 at 16:47
0

When you are working with Kotlin in Android, a library we can’t miss is Anko.

Here i added snippet of code

async {
    val result = URL("<api call>").readText()
    uiThread { 
        Log.d("Request", result)
        longToast("Request performed") 
    }
}

or else you can go with plain AsyncTask

class GetWeatherAsyncTask : AsyncTask<Params, Progress, Result>() {

    override fun onPreExecute() {
        // Before doInBackground
    }

    override fun doInBackground(vararg params: Params?): Progress {
        // ...
        publishProgress(progressResult)

        return result
    }

    override fun onProgressUpdate(vararg values: Progress?) {
       // use progressResult to do things such as updating UI...
    }

    override fun onPostExecute(result: Result?) {
        // Done: use result which is returned from doInBackground()
    }
}
Iyyanarappan
  • 145
  • 1
  • 7
  • Well, AsyncTask is also a way, but I want to do it with the basic kotlin co-routine library (experimental one), to understand deeply how co-routine works – Pratik Burkhawala Jul 16 '18 at 17:45