Skip to content

Instantly share code, notes, and snippets.

View dmytrodanylyk's full-sized avatar

Dmytro Danylyk dmytrodanylyk

View GitHub Profile
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
try {
val task = async(bgContext) { dataProvider.loadData("Task") }
val result = task.await() // non ui thread, suspend until task is finished
view.showData(result) // ui thread
} catch (e: RuntimeException) {
e.printStackTrace()
var job: Job? = null
fun startPresenting() {
job = loadData()
}
fun stopPresenting() {
job?.cancel()
}
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task = async(bgContext) { dataProvider.loadData("Task") }
// non ui thread, suspend until the task is finished or return null in 2 sec
val result = withTimeoutOrNull(2, TimeUnit.SECONDS) { task.await() }
view.showData(result) // ui thread
}
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task1 = async(bgContext) { dataProvider.loadData("Task 1") }
val task2 = async(bgContext) { dataProvider.loadData("Task 2") }
val result = "${task1.await()} ${task2.await()}" // non ui thread, suspend until finished
view.showData(result) // ui thread
}
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
// non ui thread, suspend until task is finished
val result1 = async(bgContext) { dataProvider.loadData("Task 1") }.await()
// non ui thread, suspend until task is finished
val result2 = async(bgContext) { dataProvider.loadData("Task 2") }.await()
val result = "$result1 $result2" // ui thread
private fun loadData() = launch(uiContext) {
view.showLoading() // ui thread
val task = async(bgContext) { dataProvider.loadData("Task") }
val result = task.await() // non ui thread, suspend until finished
view.showData(result) // ui thread
}
// dispatches execution onto the Android main UI thread
private val uiContext: CoroutineContext = UI
// represents a common pool of shared threads as the coroutine dispatcher
private val bgContext: CoroutineContext = CommonPool
class NewPresenter(private val todoDao: TodoDao) {
private var description: CharSequence? = null
fun bind(view: TodoView) {
todoDao.all()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view.updateTodos(it) }
}
// MainActivity.java
...
private void someMethod(int a, int b, int c, int d) {
if (a > b) {
if (b > c) {
if (c > d) {
if (d > a) {
// some logic
apply plugin: 'com.android.application'
apply from: "$project.rootDir/tools/script-pmd.gradle"
...