Skip to content

Instantly share code, notes, and snippets.

Avatar

Dmytro Danylyk dmytrodanylyk

View GitHub Profile
View MainPresenter.kt
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()
View MainPresenter.kt
var job: Job? = null
fun startPresenting() {
job = loadData()
}
fun stopPresenting() {
job?.cancel()
}
View MainPresenter.kt
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
}
View MainPresenter.kt
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
}
View MainPresenter.kt
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
View MainPresenter.kt
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
}
View CoroutineContext.kt
// 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
View NewPresenter.kt
class NewPresenter(private val todoDao: TodoDao) {
private var description: CharSequence? = null
fun bind(view: TodoView) {
todoDao.all()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view.updateTodos(it) }
}
View MainActivity.java
// 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
View build.gradle
apply plugin: 'com.android.application'
apply from: "$project.rootDir/tools/script-pmd.gradle"
...