Slide 1

Slide 1 text

Android Dev Summit 2019 extended Seoul LiveData with Coroutines and Flow ੉਋୸ kakaopay

Slide 2

Slide 2 text

dependencies { implementation knowledgebase('Android Architecture Component') // LiveData, ViewModel implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0' // viewModelScope implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-rc03' // lifecycleScope implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-rc03' // liveData coroutine builder = CoroutineLiveData // Flow ... Summary

Slide 3

Slide 3 text

Layered architecture

Slide 4

Slide 4 text

Android Dev Summit 2019 extended Seoul Layered architecture View ViewModel LiveData Repository suspend fun DataSource suspend fun UseCase suspend fun Presentation Domain Data

Slide 5

Slide 5 text

Android Dev Summit 2019 extended Seoul LiveData View ViewModel LiveData UseCase suspend fun Repository suspend fun DataSource suspend fun

Slide 6

Slide 6 text

Android Dev Summit 2019 extended Seoul DataSource suspend fun Coroutine View ViewModel LiveData UseCase suspend fun Repository suspend fun

Slide 7

Slide 7 text

Android Dev Summit 2019 extended Seoul

Slide 8

Slide 8 text

Launching coroutines

Slide 9

Slide 9 text

class MyViewModel : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext get() = SupervisorJob() + Dispatchers.Main fun doSomething() { launch { // do something } } } ViewModel

Slide 10

Slide 10 text

class MyViewModel : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext get() = SupervisorJob() + Dispatchers.Main override fun onCleared() { cancel() // coroutineContext.cancel() } } ViewModel

Slide 11

Slide 11 text

class MyViewModel : ViewModel() { fun doAnything() { GlobalScope.launch { // do anything } } } ViewModel

Slide 12

Slide 12 text

androidx.lifecycle: lifecycle-viewmodel-ktx:2.1.0

Slide 13

Slide 13 text

class MyViewModel : ViewModel() { init { viewModelScope.launch { // do something } } } ViewModel with viewModelScope

Slide 14

Slide 14 text

ViewModel with viewModelScope val ViewModel.viewModelScope: CoroutineScope get() { val scope: CoroutineScope? = this.getTag(JOB_KEY) if (scope != null) { return scope } return setTagIfAbsent(JOB_KEY, CloseableCoroutineScope( SupervisorJob() + Dispatchers.Main )) }

Slide 15

Slide 15 text

internal class CloseableCoroutineScope( context: CoroutineContext ) : Closeable, CoroutineScope { override val coroutineContext: CoroutineContext = context override fun close() { coroutineContext.cancel() } ViewModel with viewModelScope

Slide 16

Slide 16 text

ViewModel with viewModelScope public abstract class ViewModel { final void clear() { mCleared = true; if (mBagOfTags != null) { synchronized (mBagOfTags) { for (Object value : mBagOfTags.values()) { closeWithRuntimeException(value); } } } onCleared(); }

Slide 17

Slide 17 text

class MyViewModel : ViewModel() { override fun onCleared() { viewModelScope.launch { // do something } } } ViewModel with viewModelScope

Slide 18

Slide 18 text

androidx.lifecycle: lifecycle-runtime-ktx:2.2.0-rc03

Slide 19

Slide 19 text

class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { // do something } } } Activities & Fragments with lifecycleScope

Slide 20

Slide 20 text

val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope get() = lifecycle.coroutineScope val Lifecycle.coroutineScope: LifecycleCoroutineScope get() { ... val newScope = LifecycleCoroutineScopeImpl( this, SupervisorJob() + Dispatchers.Main.immediate ) ... } Activities & Fragments with lifecycleScope

Slide 21

Slide 21 text

class MyActivity : AppCompatActivity() { override fun onDestroy() { super.onDestroy() lifecycleScope.launch { // do something } } } Activities & Fragments with lifecycleScope

Slide 22

Slide 22 text

class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { // do something } lifecycleScope.launchWhenResumed { // do something } } } Activities & Fragments with lifecycleScope

Slide 23

Slide 23 text

Activities & Fragments with lifecycleScope class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { ... lifecycleScope.launch { lifecycleScope.launchWhenResumed { repeat(100) { delay(30) textView.text = (it + 1).toString() } }

Slide 24

Slide 24 text

launch launchWhenResumed VS

Slide 25

Slide 25 text

class MyFragment : Fragment() { init { lifecycleScope.launchWhenCreated { // do something } lifecycleScope.launchWhenStarted { // do something } } } Activities & Fragments with lifecycleScope

Slide 26

Slide 26 text

Application scope or WorkManager https://www.youtube.com/watch?v=B8ppnjGPAGE&t=910s Application

Slide 27

Slide 27 text

LiveData coroutine builder

Slide 28

Slide 28 text

ViewModel + LiveData class MyViewModel : ViewModel() { private val _result = MutableLiveData() val result: LiveData = _result init { viewModelScope.launch { val computationResult = doComputation() _result.value = computationResult } } }

Slide 29

Slide 29 text

ViewModel + LiveData class MyViewModel : ViewModel() { private val _result = MutableLiveData() val result: LiveData = _result init { viewModelScope.launch(Dispatchers.IO) { val computationResult = doComputation() _result.postValue(computationResult) } } }

Slide 30

Slide 30 text

androidx.lifecycle: lifecycle-livedata-ktx:2.2.0-rc03

Slide 31

Slide 31 text

liveData coroutine builder class MyViewModel : ViewModel() { val result = liveData { emit(doComputation()) } }

Slide 32

Slide 32 text

liveData coroutine builder fun liveData(...): LiveData = CoroutineLiveData(context, timeoutInMs, block) internal class CoroutineLiveData( ... ) : MediatorLiveData() { init { ... val scope = CoroutineScope( Dispatchers.Main.immediate + context + supervisorJob) ... } }

Slide 33

Slide 33 text

Dispatchers.Main.immediate ?

Slide 34

Slide 34 text

liveData coroutine builder class MyViewModel : ViewModel() { val result = liveData(Dispatchers.IO) { emit(doComputation()) } }

Slide 35

Slide 35 text

liveData coroutine builder class MyViewModel : ViewModel() { val result = liveData { emit(doComputation()) emitSource(repo.fetchSomething()) } } class MyRepository { fun fetchSomething(): LiveData { ...

Slide 36

Slide 36 text

liveData coroutine builder class MyViewModel : ViewModel() { private val itemId = MutableLiveData() val item = itemId.switchMap { liveData { emit(fetchItem(it)) } } }

Slide 37

Slide 37 text

LiveData coroutine builder + with flow

Slide 38

Slide 38 text

class MyDataSource { private val weather: String get() = listOf("Sunny", "Rainy", "Cloudy").shuffled().first() fun fetchWeather(): LiveData = liveData { fun fetchWeatherFlow() = flow { while (true) { delay(2_000) emit(weather) } } } Data Source

Slide 39

Slide 39 text

emit N values // LiveData -> LiveData val currentWeather: LiveData = dataSource.fetchWeather()

Slide 40

Slide 40 text

emit N values // LiveData -> LiveData val currentWeather: LiveData = dataSource.fetchWeather() // flow -> LiveData val currentWeatherFlow: LiveData = liveData { dataSource.fetchWeatherFlow().collect { emit(it) } }

Slide 41

Slide 41 text

emit N values // LiveData -> LiveData val currentWeather: LiveData = dataSource.fetchWeather() // flow -> LiveData val currentWeatherFlow: LiveData = dataSource.fetchWeatherFlow().asLiveData()

Slide 42

Slide 42 text

emit 1 + emit N // LiveData -> LiveData val currentWeather: LiveData = liveData { emit(LOADING_STRING) emitSource(dataSource.fetchWeather()) }

Slide 43

Slide 43 text

emit 1 + emit N // LiveData -> LiveData val currentWeather: LiveData = liveData { emit(LOADING_STRING) emitSource(dataSource.fetchWeather()) } // flow -> LiveData val currentWeatherFlow: LiveData = liveData { emit(LOADING_STRING) emitSource( dataSource.fetchWeatherFlow().asLiveData() ) }

Slide 44

Slide 44 text

emit 1 + emit N // LiveData -> LiveData val currentWeather: LiveData = liveData { emit(LOADING_STRING) emitSource(dataSource.fetchWeather()) } // flow -> LiveData val currentWeatherFlow: LiveData = dataSource.fetchWeatherFlow() .onStart { emit(LOADING_STRING) } .asLiveData()

Slide 45

Slide 45 text

Transformation // LiveData -> LiveData val currentWeather: LiveData = dataSource.fetchWeather().switchMap { liveData { emit(heavyTransformation(it)) } }

Slide 46

Slide 46 text

Transformation // LiveData -> LiveData val currentWeather: LiveData = dataSource.fetchWeather().switchMap { liveData { emit(heavyTransformation(it)) } } // flow -> LiveData val currentWeatherFlow: LiveData = dataSource.fetchWeatherFlow() .map { heavyTransformation(it) } .asLiveData()

Slide 47

Slide 47 text

cancelling Coroutine LiveData

Slide 48

Slide 48 text

val currentWeather: LiveData = dataSource.fetchWeatherFlow().map { it.toUpperCase() }.onStart { emit("ON START") }.asLiveData() cancelling CoroutineLiveData

Slide 49

Slide 49 text

fun Flow.asLiveData( context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT ): LiveData = liveData(context, timeoutInMs) { collect { emit(it) } } fun liveData( context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT, @BuilderInference block: suspend LiveDataScope.() -> Unit ): LiveData = CoroutineLiveData(context, timeoutInMs, block) cancelling CoroutineLiveData

Slide 50

Slide 50 text

internal class CoroutineLiveData( ... ) : MediatorLiveData() { init { ... blockRunner = BlockRunner( ... ) } override fun onInactive() { super.onInactive() blockRunner?.cancel() } } cancelling CoroutineLiveData

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

internal class BlockRunner( … ) { fun cancel() { ... cancellationJob = scope.launch(Dispatchers.Main.immediate) { delay(timeoutInMs) if (!liveData.hasActiveObservers()) { ... runningJob?.cancel() runningJob = null } } … cancelling CoroutineLiveData

Slide 53

Slide 53 text

val currentWeather: LiveData = dataSource.fetchWeatherFlow().map { it.toUpperCase() }.onStart { emit("ON START") }.asLiveData() }.asLiveData(parentJob) }.asLiveData(viewModelScope.coroutineContext) cancelling CoroutineLiveData

Slide 54

Slide 54 text

ViewModel, Repository, DataSource patterns

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

CodeLab

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

Testing

Slide 59

Slide 59 text

Testing Coroutines on Android (Android Dev Summit '19)

Slide 60

Slide 60 text

Android Dev Summit 2019 extended Seoul References • LiveData with Coroutines and Flow (Android Dev Summit '19) https://www.youtube.com/watch?v=B8ppnjGPAGE&t=416s • LiveData Overview https://developer.android.com/topic/libraries/architecture/livedata • Use Kotlin coroutines with Architecture components https://developer.android.com/topic/libraries/architecture/coroutines • Easy Coroutines in Android: viewModelScope https://medium.com/androiddevelopers/easy-coroutines-in-android-viewmodelscope-25bffb605471 • Lessons learnt using Coroutines Flow in the Android Dev Summit 2019 app https://medium.com/androiddevelopers/lessons-learnt-using-coroutines-flow-4a6b285c0d06 • iosched adssched2019 branch : https://github.com/google/iosched/tree/adssched2019

Slide 61

Slide 61 text

Android Dev Summit 2019 extended Seoul References • CodeLab : Advanced Coroutines with Kotlin Flow and LiveData https://codelabs.developers.google.com/codelabs/advanced-kotlin-coroutines/index.html?index=.. %2F..index#0 • Testing Coroutines on Android (Android Dev Summit '19) https://www.youtube.com/watch?v=KMb0Fs8rCRs&t=11s • Cold flows, hot channels https://medium.com/@elizarov/cold-flows-hot-channels-d74769805f9 • Simple design of Kotlin Flow https://medium.com/@elizarov/simple-design-of-kotlin-flow-4725e7398c4c • Kotlin Flows and Coroutines https://medium.com/@elizarov/kotlin-flows-and-coroutines-256260fb3bdb

Slide 62

Slide 62 text

Thank you