Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active July 25, 2019 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchtabian/774c80d292ada780e8867b43744c43b4 to your computer and use it in GitHub Desktop.
Save mitchtabian/774c80d292ada780e8867b43744c43b4 to your computer and use it in GitHub Desktop.
package com.codingwithmitch.coroutineexamples
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
setNewText("Click!")
fakeApiRequest()
}
}
private fun setNewText(input: String){
val newText = text.text.toString() + "\n$input"
text.text = newText
}
private suspend fun setTextOnMainThread(input: String) {
withContext (Main) {
setNewText(input)
}
}
private fun fakeApiRequest() {
GlobalScope.launch(IO) {
if (getResult1FromApi() == "Result #1") {
setTextOnMainThread("Got Result #1")
if (getResult2FromApi() == "Result #2") {
setTextOnMainThread("Got Result #2")
} else {
setTextOnMainThread("Couldn't get Result #2")
}
} else {
setTextOnMainThread("Couldn't get Result #1")
}
}
}
private suspend fun getResult1FromApi(): String {
delay(2000)
return "Result #1"
}
private suspend fun getResult2FromApi(): String {
delay(1000)
return "Result #2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment