Skip to content

Instantly share code, notes, and snippets.

@Evin1-
Last active August 5, 2020 01:43
Show Gist options
  • Save Evin1-/f1484f24d01ed2f3f7f37a7f132072ad to your computer and use it in GitHub Desktop.
Save Evin1-/f1484f24d01ed2f3f7f37a7f132072ad to your computer and use it in GitHub Desktop.
Loop Cupcakes. Migrating AsyncTask to RxJava.
// build.gradle (:app)
android {
//..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
//.. https://github.com/ReactiveX/RxAndroid
//.. https://github.com/ReactiveX/RxJava
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'io.reactivex.rxjava3:rxjava:3.0.5'
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Creates a flow of exactly one item, switches to a new thread to perform the operation
* using the subscribeOn operator, and comes back to the main thread after the chain is
* fully computed using the observeOn operator, the logging and error handling are run
* on the main thread. This will print the String "Result is 4" to the Logcat */
Single.fromCallable { doExpensiveFunction(2) }
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ Log.d("TAG_", "Result is: $it") }, { Log.e("TAG_ ", "Error: $it") })
}
/* Since we're creating an RxJava Single, this method will run on a worker thread created
* by Schedulers.newThread, if we called this from anywhere else without the fromCallable,
* this would run on the main thread and would crash or ANR a production app */
private fun doExpensiveFunction(input: Int): Int {
/* Thread.sleep simulates a long running operation */
Thread.sleep(2000)
return input * input
}
}
class OldMainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Creates and executes the AsyncTask */
val execute = OldTask().execute(2)
val result = execute.get()
/* Prints the string "Result is 4" to the Logcat. This is run on the main thread */
Log.d("TAG_ ", "Result is $result")
}
}
/* https://developer.android.com/reference/android/os/AsyncTask */
class OldTask : AsyncTask<Int, Unit, Int>() {
/* This method runs on a worker thread */
override fun doInBackground(vararg param: Int?): Int {
/* Thread.sleep simulates a long running operation */
Thread.sleep(2000)
val input = param.getOrNull(0) ?: 0
return input * input
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment