---
# System prepended metadata

title: Android Learning

---

# Android Learning 

## all the ways to handle Configuration Changes (both in an XML world and in a Compose world)
what survives different kinds of "death" (process, system, app)

What is the difference between force stopping an app and process death?
TODO 

"Process death will happen when the Android system decides your backgrounded app needs to be killed from memory to make room for other apps.
When your app is resumed after a process death, the activity that the user was last using will be recreated and will call its “onCreate” method."


Is system-intiated vs unexepected process death any different?
TODO

You can use a combination of [`onSaveInstanceState()`](https://developer.android.com/reference/android/app/Activity#onsaveinstancestate), [`ViewModel`](https://developer.android.com/reference/androidx/lifecycle/ViewModel) objects, and persistent storage to save and restore the UI state of your activity across configuration changes.

ViewModel retains the data in memory, which means it is cheaper to retrieve than data from the disk or the network. A ViewModel is associated with an activity (or some other lifecycle owner) - it stays in memory during a configuration change and the system automatically associates the ViewModel with the new activity instance that results from the configuration change.

ViewModels are automatically destroyed by the system when your user backs out of your activity or fragment or if you call `finish()`, which means the state will be cleared as the user expects in these scenarios.

Unlike saved instance state, ViewModels are destroyed during a system-initiated process death. This is why you should use ViewModel objects in combination with `onSaveInstanceState()` (or some other disk persistence), stashing identifiers in `savedInstanceState` to help view models reload the data after system death.

## explain, compare, contrast MVVM, MVI, MVP, MVC

Round-up

Each of these architectures offer plenty in the domain of separation of concerns, testability, and modularity, but each of them have advantages and disadvantages that they individually offer.

In a nutshell, MVP is simple but involves a heavy lifecycle problem and doesn’t offer much that the architectures don’t, apart from its simplicity.

MVVM relies heavily on Android Architecture Components and can be difficult to implement correctly with DI, but can survive lifecycle and configuration changes, as well as having multiple View components making use of the same View Model at the same time.

MVI offers a strong adherence to SSOT and the View State provides a good data representation of the View, but has the heavily complex need for creating and maintaining State Reducers, on top of having the same lifecycle problem as MVP.

So after carefully weighing the advantages and disadvantages of each architecture, the council has decided that the objective best architectural pattern for Android in 2020 is…. MVVM!

The lifecycle problem of MVP and MVI is a big deal. This creates easy opportunities for memory leaks, bugs and crashes. MVVM solving this is a huge advantage.

On top of this, the fact that MVVM can have multiple Views making use of the same instance of a View Model is a unique advantage that the others simply don’t have. If you had multiple fragments, you would have to create a Presenter for each of them.

MVI does make use of View States to represent how the View should render but the View Model fulfils that exact role within the class itself. The state of the LiveData within the View Model should also be a representation of how the View renders itself.

Now what’s the main disadvantage of MVVM, DI complexity. MVI also brings a high level of complexity with state reducers. The difference is once the DI is set up in an MVVM app, maintaining it requires minimal effort. The complexity curve has been conquered. With MVI, you have to create State Reducers for every activity and what the State Reducer needs to accomplish in each case will be different. MVP doesn’t have this disadvantage of complexity, but the advantages that MVVM brings to the table more than makes up for it.

The winner is MVVM.


When a presenter in instantiated by a View, the view has to pass a `context` into the presenter's constructor. 

Question: If you have to pass in a context to a ViewModel's constructor, have you broken the ideal pattern of MVVM?


A key difference between architectures is whether the P/C/VM has hard references to the view (e.g. context of the view)



## explain coroutines and their scopes

> One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine.

> A _coroutine_ is an instance of suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.


[launch](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html) is a _coroutine builder_.

[delay](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html) is a special _suspending function_. It _suspends_ the coroutine for a specific time. Suspending a coroutine does not _block_ the underlying thread, but allows other coroutines to run and use the underlying thread for their code.

[runBlocking](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) is also a coroutine builder that bridges the non-coroutine world of a regular `fun main()` and the code with coroutines inside of `runBlocking { ... }` curly braces. This is highlighted in an IDE by `this: CoroutineScope` hint right after the `runBlocking` opening curly brace.

[runBlocking](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) and [coroutineScope](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) builders may look similar because they both wait for their body and all its children to complete. The main difference is that the [runBlocking](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) method _blocks_ the current thread for waiting, while [coroutineScope](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) just suspends, releasing the underlying thread for other usages. Because of that difference, [runBlocking](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) is a regular function and [coroutineScope](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) is a suspending function.

A [launch](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html) coroutine builder returns a [Job](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html) object that is a handle to the launched coroutine and can be used to explicitly wait for its completion. (via `job.join()`)


#### Structured Concurrency
Coroutines follow a principle of **structured concurrency** which means that new coroutines can be only launched in a specific [CoroutineScope](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html) which delimits the lifetime of the coroutine.


In a real application, you will be launching a lot of coroutines. Structured concurrency ensures that they are not lost and do not leak. An outer scope cannot complete until all its children coroutines complete. Structured concurrency also ensures that any errors in the code are properly reported and are never lost.

Coroutines always execute in some context represented by a value of the [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/) type, defined in the Kotlin standard library.


https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/04_Suspend

https://github.com/Kotlin/kotlinx.coroutines

https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjcyIiwiY29kZSI6ImltcG9ydCBrb3RsaW54LmNvcm91dGluZXMuKlxuXG5mdW4gbWFpbigpID0gcnVuQmxvY2tpbmcge1xuICAgIHJlcGVhdCgxMDAwMCkgeyAvLyBsYXVuY2ggYSBsb3Qgb2YgY29yb3V0aW5lc1xuICAgICAgICBsYXVuY2gge1xuICAgICAgICAgICAgZGVsYXkoNTAwMEwpXG4gICAgICAgICAgICBwcmludChcIi5cIilcbiAgICAgICAgfVxuICAgIH1cbn0iLCJwbGF0Zm9ybSI6ImphdmEiLCJhcmdzIjoiIn0=

There are two functions in Kotlin to start the coroutines which are as follows:
-   `launch{}`
-   `async{}`

The difference is that the `launch{}` returns a `Job` and does not carry any resulting value whereas the `async{}` returns an instance of `Deferred<T>`, which has an `await()` function that returns the result of the coroutine like we have future in Java in which we do `future.get()` to get the result.

Coroutine Scopes
​​There are basically **3 scopes** in Kotlin coroutines:

1.  Global Scope
2.  LifeCycle Scope
3.  ViewModel Scope

#### Global Scope
When Coroutines are launched within the global scope, they live long as the application does. If the coroutines finish it’s a job, it will be destroyed and will not keep alive until the application dies, but let’s imagine a situation when the coroutines has some work or instruction left to do, and suddenly we end the application, then the coroutines will also die, as the maximum lifetime of the coroutine is equal to the lifetime of the application. Coroutines launched in the global scope will be launched in a separate thread.


The main problem with the coroutines launched in the global scope is that when the activity in which coroutines is launched dies, the coroutines will not die with the activity, since the lifetime of coroutines is decided on the basis of application lifetime, not the activity lifetime.

#### Lifecycle Scope
The lifecycle scope is the same as the global scope, but the only difference is that when we use the lifecycle scope, all the coroutines launched within the activity also dies when the activity dies. It is beneficial as our coroutines will not keep running even after our activity dies.


#### ViewModel Scope
It is also the same as the lifecycle scope, only difference is that the coroutine in this scope will live as long the view model is alive. ViewModel is a class that manages and stores the UI-related data by following the principles of the [lifecycle system in android.](https://www.geeksforgeeks.org/activity-lifecycle-in-android-with-demo-app/)

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/


## explain threads

## explain Context and their scopes

## explain, compare, contrast LiveData, State/MutableState, Flow
Data structures in Kotlin (e.g. List, ArrayList, Array, Map)



