Slide 1

Slide 1 text

Coroutines + Android Framework Antonio Leiva

Slide 2

Slide 2 text

Coroutines + Android Framework =

Slide 3

Slide 3 text

What are coroutines?

Slide 4

Slide 4 text

Coroutines for Android - Some libraries ● kotlinx-coroutines-android (by Kotlin team) ● async/await (by Metalab) ● AsyncAwait-Android (by Niek Haarman) ● Anko (by Kotlin team)

Slide 5

Slide 5 text

Anko - coroutines embedded into the framework ● Most async functions start from a UI event ● What happens if we embed coroutines into listeners?

Slide 6

Slide 6 text

Anko - coroutines embedded into the framework textView.onClick { val res = bg { findBackgroundColor() } textView.setBackgroundColor(res.await()) }

Slide 7

Slide 7 text

Some examples - SearchView searchView.onQueryTextListener { onQueryTextChange { text -> progress.visible() val res = bg { doSearch(text) } updateContent(res.await()) progress.invisible() false } }

Slide 8

Slide 8 text

Some examples - OnMenuItemClick toolbar.onMenuItemClick { when (it?.itemId) { R.id.action_edit -> startActivity() R.id.action_save -> { bg { save() }.await() toast("Saved") } R.id.action_delete -> { bg { delete() }.await() toast("Deleted") } } }

Slide 9

Slide 9 text

Does it fit into an architecture? searchView.onQueryTextListener { onQueryTextChange { presenter.onSearchTextChanged(it); false } } --- suspend fun onSearchTextChanged(search: String?) { view.showProgress() val res = bg { searchTextInteractor(search) } updateContent(res.await()) view.hideProgress() }

Slide 10

Slide 10 text

Does it fit into an architecture? toolbar.onMenuItemClick { item -> item?.itemId?.let { presenter.onActionClicked(when (it) { R.id.action_edit -> Action.Edit R.id.action_save -> Action.Save R.id.action_delete -> Action.Delete else -> throw IllegalStateException("Unknown Action") }) } } suspend fun onActionClicked(action: Action) { when (action) { Action.Edit -> view.navigateToEdit() Action.Save -> { bg { save() }.await() view.showMessage("Saved") } Action.Delete -> { bg { delete() }.await() view.showMessage("Deleted") } } }

Slide 11

Slide 11 text

Does it make sense?

Slide 12

Slide 12 text

Does it make sense? Probably not

Slide 13

Slide 13 text

Does it make sense? fun onSearchTextChanged(search: String?) { async(UI) { view.showProgress() val res = bg { searchTextInteractor(search) } updateContent(res.await()) view.hideProgress() } }

Slide 14

Slide 14 text

Thanks! Questions? 3 - 4 Junio: Bootcamp Kotlin online https/devexperto.com/bootcamp