Skip to content

Instantly share code, notes, and snippets.

@FareesHussain
Last active July 30, 2020 15:53
Show Gist options
  • Save FareesHussain/db1ddd511a2c78d1637a9ca23aa62b80 to your computer and use it in GitHub Desktop.
Save FareesHussain/db1ddd511a2c78d1637a9ca23aa62b80 to your computer and use it in GitHub Desktop.
usage of coroutines in different aspects

Coroutines

description

best alternative for asynctask and Rxjava

dependencies

dependencies{
	..
	// Coroutines
	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5'
	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5'
	

	// Coroutine Lifecycle Scopes
	implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
	implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
	
	
	// Kotlin Extensions and Coroutines support for Room
	implementation "androidx.room:room-ktx:2.2.5"
}
  • declare a coroutines scope of Mainthread
  • inside the onCreate fun launch the scope
  • add the startActivity function

demo

class SplashActivity : AppCompatActivity() {

	private lateinit var binding : ActivitySplashBinding
	val activityScope = CoroutineScope(Dispatchers.Main)

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		binding = ActivitySplashBinding.inflate(layoutInflater)
		setContentView(binding.root)

		Glide.with(this).load(R.drawable.weathericon).into(binding.imageView)

		activityScope.launch {
			delay(3000)
			startActivity(Intent(this@SplashActivity,MainActivity::class.java))
			finish()
		}
	}

	override fun onPause() {
		activityScope.cancel()
		super.onPause()
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment