Advantages of Kotlin over Java
Concise syntax:
Kotlin’s syntax is more concise, reducing boilerplate code and making it easier to read and write.
Null safety:
Kotlin has a null safety feature that can help reduce the number of runtime exceptions caused by null pointer errors. This can improve the overall reliability of Kotlin applications.
Functional programming support:
Kotlin supports functional programming features such as lambda expressions, function types, and higher-order functions. This can make Kotlin code more concise and expressive.
Interoperability with Java:
Kotlin is fully interoperable with Java.
This means that Kotlin code can be used in Java projects and vice versa. This can make it easier to migrate from Java to Kotlin or to use Kotlin in existing Java projects.
Coroutines
Kotlin’s built-in support for coroutines simplifies asynchronous programming and improves performance.
Tooling and Community Support
Kotlin has excellent tooling support, including IDE plugins for popular development environments. It also has a growing and active community, with learning resources and libraries available.
Data class
The data class in Kotlin is used to hold the data. This data class contains some utility functions
that are often derivable from the data. With the help of the data class, you don't need to write
the boiler plate code. The compiler automatically generates all the getter and setter for all the
data class properties. It is designed to automatically generate common methods such as
equals(), hashCode(), toString(), and copy() based on the properties defined in the class
Companion Objects
A companion object is a special object that is associated with a class. It can be accessed
using the name of the class. Companion objects are often used to define class-level functions
and variables, and they can also be used to implement interfaces.
Safe call, Elvis and Not Null Assertion operator(How do you handle nullability in Kotlin?)
Safe call:
· The safe call operator (?.) Kotlin is used to access properties or methods of a
nullable variable. If the variable is null, the safe call operator will return null instead of
crashing the program. This is a great way to avoid null pointer exceptions in Kotlin
Elvis operator:
· It is used to return the first expression if it is not null, or it returns the second
expression otherwise. The operator is written as ?:
· val greeting = str ?: "Hello", in this example greeting will be str if str is not null or else
greeting will be hello.
Not-null assertion:
· It is used to explicitly tell the compiler that we are sure that the value of the
expression is not null. If the value is null, a NullPointerException will be thrown.
Constructors
· The primary constructor is used to initialize the class and must be declared in the
class header. It can have parameters, which are used to initialize the class properties.
· Secondary constructors are used to provide additional initialization logic. They are
declared in the class body and must delegate to the primary constructor.
class Person(val name: String) { // Primary Constuctor
constructor(name: String, age: Int) : this(name) { // Secondary constructor
initializing primary constructor
// This code will be executed after the primary constructor has been called.
}
val mutableList or var immutableList
val mutableList is a mutable list, which means that its elements can be added or removed. var
immutableList is an immutable list, which means that its elements cannot be added or
removed
String Interpolation in Kotlin
If you want to use some variable or perform some operation inside a string then String
Interpolation can be used. You can use the $ sign to use some variable in the string or can
perform some operation in between {} sign.
fun main() {
val name = "John"
val age = 30
val message = "My name is $name and I am $age years old."
println(message) // Output: My name is John and I am 30 years old.
}
Visibility modifiers in Kotlin
public, private, protected
· internal: Internal declarations are visible within the same module. A module is a set
of Kotlin files compiled together, such as an IntelliJ module or a Gradle module.
· protected internal: A combination of protected and internal. Protected internal
declarations are visible within the same module and subclasses.
· private internal: A combination of private and internal. Private internal declarations
are visible within the same file and the same module.
Lateinit
(lateinit is late initialization) The lateinit keyword in Kotlin is used to declare a non-null type
variable without initializing it. isInitialized, method can be used to verify the variable is initialized or not.
Here are some examples of when you might want to use lateinit:
· When you are using dependency injection to initialize a property.
· When you are writing a unit test and you need to initialize a property in the setup
method.
· When you are creating a class that will be used in a variety of contexts and you don't
know when the property will be initialized.
It is important to note that you should only use lateinit for properties that will be initialized at
some point in the future. If you try to access a lateinit property before it has been initialized,
you will get an error.
Lazy initialization
Lazy initialization in Kotlin is a feature that allows you to initialize a property only when it is first used. This can be useful for properties that have a long initialization time, or for properties that you may not need to use in your code.
To use lazy initialization, you can use the lazy function. The lazy function takes a lambda expression as its argument. The lambda expression is executed when the property is first accessed, and the result of the lambda expression is stored in the property.
val file by lazy {
val inputStream = FileInputStream("myfile.txt")
val reader = BufferedReader(InputStreamReader(inputStream))
reader.readText()
}
Lazy initialization is a powerful feature that can help you to improve the performance
De-structuring declarations
This allows user to extract multiple values from an object or a data structure and assign them
to individual variables. It simplifies the process of extracting and using specific elements from
complex objects. Destructuring declarations are typically used with data classes, arrays, and
other structures that provide component functions
data class Point(val x: Int, val y: Int)
fun main() {
val point = Point(3, 4)
val (x, y) = point
println("x: $x, y: $y") // Output: x: 3, y: 4
}
@JvmStatic, @JvmOverloads, and @JvmFiled in Kotlin?
· @JvmStatic: This annotation is used to tell the compiler that the method is a static
method and can be used in Java code.
· @JvmOverloads: To use the default values passed as an argument in Kotlin code
from the Java code, we need to use the @JvmOverloads annotation.
· @JvmField: To access the fields of a Kotlin class from Java code without using any
getters and setters, we need to use the @JvmField in the Kotlin code.
FlatMap and Map
· FlatMap is used to combine all the items of lists into one list.
· Map is used to transform a list based on certain conditions.
val data = listOf(Data(listOf("a","b","c")),Data(listOf("1","2","3")))
val combined = data.flatMap { it.items }
println(combined)
val combinedMap = data.map { it.items }
println(combinedMap)
Output
[a, b, c, 1, 2, 3]
[[a, b, c], [1, 2, 3]]
Serializable and Parcelable
Scope functions
These allow you to perform operations on an object within its context. It provides a temporary
scope when you call the function on the object with a lambda expression
The five scope functions in Kotlin are: apply, run, with, let, also
apply:
· apply is used when you want to modify the properties or invoke functions on an
object and return the modified object itself.
· It is often used for configuring and initializing objects, such as setting properties or
adding elements to a collection.
run:
· run is used when you want to execute a block of code on an object and return the
result of that block.
· It allows you to access the object’s properties and functions directly within the block
· The “run” function is useful when you want to perform a series of operations on an
object
· It is useful for performing operations and returning a result based on the object's
state.
with:
· with is used when you want to operate on an object without the need to call it
explicitly.
· It allows you to work with the object's properties or functions directly within a block.
let:
· let is used when you want to perform a series of operations on a non-null object and
provide a safe way to handle null references.
· It is often used for chaining operations or transformations on objects.
also:
· also is used to perform some additional operations on an object within a block of
code without changing the object and it returns the original object.
· It is used in cases where actions are taken on the object rather than fields of the
object.
What are Coroutines
A coroutine can be thought of as a worker that performs some long-running/memory-intensive
operations asynchronously. The asynchronous nature of a coroutine ensures that any long
running/memory-intensive operations do not block the main thread of execution. In essence, it
takes a block of code and runs it on a particular thread. 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
Why Coroutines
The current framework which is available to handle multithreading leads to callback hells and
blocking states because we do not have any other simple way to guarantee thread-safe
execution.
A coroutine is a very efficient and complete framework to manage concurrency in a more
performant and simple way.
Now that, we have understood what are coroutines when it comes to cooperation between the
functions. There are endless possibilities that open up because of the cooperative nature of
functions.
A few of the possibilities are as follows:
· It can execute a few lines of functionA and then execute a few lines of functionB and
then again, a few lines of functionA and so on. This will be helpful when a thread is
sitting idle and not doing anything, in that case, it can execute a few lines of another
function. This way, it can take full advantage of the thread. Ultimately cooperation helps
in multitasking.
· It will enable writing asynchronous code in a synchronous way. We will talk about this
later in this article.
Overall, the Coroutines make multitasking very easy.
So, we can say that Coroutines and the threads both are multitasking. But the difference is
that threads are managed by the OS and coroutines by the users as it can execute a few lines
of function by taking advantage of the cooperation.
Suspend
Suspend function is the building block of the Coroutines and a function that could be started,
paused, and resume. Suspend functions are only allowed to be called from a coroutine or
another suspend function.
launch-vs-async-in-Kotlin-coroutines
launch and async are the functions in Kotlin to start the Coroutines.
launch{} returns a Job and does not carry any resulting value. async{} returns an instance of
Deferred<T>, which has an await() function that returns the result of the coroutine.
· launch: fire and forget.
· async: perform a task and return a result.
It returns a job object which we can use to get a job's status or to cancel it.
This deferredJob can also be used to get the job status or to cancel it(similar to launch)
Another Major difference between launch and async is in the terms of exception
handling.
launch: Whenever there is an exception in this block the app will crash if we have not handled it.
async: if any exception happens inside the async block, it is stored inside the result obj I.e.
Deffered and the exception won’t be delivered inside the block unless we manually handle it.
This will crash this will not crash but exception is not captured here
To handle or capture the exception inside the block we need to handle it.
Fetching the result or exception from deferred obj
Dispatchers
Dispatchers is responsible for determining how the coroutine are scheduled and executed.
Allows us to specify which pool of threads the coroutines are executed. The dispatcher can be
specified as a part of the coroutine context It manages the execution context and thread on
which the coroutine runs. i.e... It helps coroutines in deciding the on which thread the task
must be done.
Dispatchers.Default : this is the default dispatcher used by coroutines, it is designed to use
for the CPU bound tasks such as filtering a large list, like to perform any operation on things
which are already present in the memory. This dispatcher uses shared pool of threads.
Dispatchers.IO: this is optimized for I/O bound tasks such as reading from and writing to files
or making network requests or fetching data from local database. It uses larger pool of threads
allowing for concurrent I/O operations.
Dispatchers.Main: this is specifically designed for UI-related tasks, this runs coroutines on
main thread, allowing us to update the user interface directly.
Dispatchers.Unconfined : this doesn’t confine coroutines to any specific any specific thread.
It starts executing coroutine in the current thread but may switch to another if needed. This is
mainly used for testing and situations where confinement is not required
Dispatchers.Immediate :The immediate dispatcher is a recently introduced dispatcher. It is
used to reduce the cost of re-dispatching the coroutine to the main thread. There is a slight
cost associated when switching the dispatcher using the withContext{} block. Using the
Immediate dispatcher ensures the following.
· If a coroutine is already executing in the main dispatcher, then the coroutine wouldn’t
be re-dispatched, therefore removing the cost associated with switching dispatchers.
· If there is a queue of coroutines waiting to get executed in the main dispatcher, the
immediate dispatcher ensures that the coroutine will be executed as immediately as
possible.
withContext() — Allows to switch the context of execution for a block of code.
Singleton Class in Kotlin
A singleton class is a class that is defined in such a way that only one instance of the class
can be created and used everywhere.
Properties of Singleton Class
The following are the properties of a typical singleton class:
Only one instance: The singleton class has only one instance and this is done by providing
an instance of the class, within the class.
Globally accessible: The instance of the singleton class should be globally accessible so that
each class can use it.
Constructor not allowed: We can use the init method to initialize our member variables.
Coroutinescope
Coroutinescope is an interface that defines scope for managing the lifecycle of coroutines.
· It helps manage the lifecycle of the coroutines within its scope, when it is cancelled it
cancels all its child coroutines
· It facilitates structed concurrency, which means that child coroutines are bound to
their parent scope. When we create coroutines within a CoroutineScope they become
child coroutines of that scope. This enables hierarchical organization and clear
ownership of coroutines.
· It provides coroutine builder functions like launch, async and runBlocking, which
allows us to create and launch coroutines within the scope.
· It provides a coroutine context, which includes a coroutine dispatcher (ex:
coroutinescope(conext=Main)
· When a coroutinescope is canceled, the cancelation signal is propagated to all
childs.
SupervisorScope
It’s a special type of coroutinescope which allows us to create a scope with supervisor job,
which modifies the behavior of coroutine failure propagation within that scope.
· It does provide fault isolation for coroutines, if one of the child coroutine fails with an
exception then the failure is contained in that specific child coroutine and does not
propagate to other child coroutines are parent scope
· It supports error handling, failure of one child coroutine does not affect the execution
of other child coroutines, allowing us to handle errors more selectively and flexibly.
Inline Functions
It is a kind of function that is declared with the keyword inline just before the function
declaration. Once a function is declared inline, the compiler does not allocate memory for this
function, instead the compiler copies the piece of code virtually at the calling place at runtime.
High order functions which let us pass the functions as params as well as return functions. But
the fact that they are stored as objects may make the use disadvantageous at times because
of the memory overhead. The thing is, each object is allocated space in memory heap and the
methods that call this method are also allocated space.
Inline functions increase the resulting byte code because of copying code, that’s why inline
usage should be for small functions and avoided for the large functions
noinline
While using an inline function and want to pass some lambda functions and not all lambda
functions as inline, then you can explicitly tell the compiler which lambda it shouldn’t inline
reified modifier
The `reified` modifier in Kotlin is used in combination with the `inline`, this modifier is often
used when working with functions that need to perform operations based on the runtime type
of a generic parameter, such as reflection or type-specific behavior
Higher-Order Function
A function which can accept a function as parameter or can return a function is called Higher
Order function. Instead of Integer, String or Array as a parameter to function, we will pass
anonymous function or lambdas
Some of the basic higher-order functions are apply, with, let, also, and run etc. in Kotlin’s
standard library.
Example 1 : Pass Lambda expression inside a higher order function as parameter
fun main(args: Array<String>) {
// Passing function body as a Lambda expressions
printStr({println("fun body passed as a Lambda expressions")})
}
// Body of this method pass by calling function here i.e println()
fun printStr(printingString: () -> Unit) {
printingString()
}
Example 2: Assign Lambda Expression to variable and pass variable as a parameter
// lambda expression
var lambdaExpression = { println("Sample String to be print") }
// higher-order function
fun higherOrderfunc( lambdaFuncParam: () -> Unit ) {
lambdaFuncParam() //invokes lambda expression
}
fun main(args: Array<String>) {
//invoke higher-order function
// passing lambda expression variable as parameter
higherOrderfunc (lambdaExpression)
}
Example 3: Function accept two parameter of Integer type and return Addition of both integers,
that function pass as a parameter
// regular function definition
fun addTwoNumbers(a: Int, b: Int): Int{
var sum = a + b
return sum
}
// higher-order function definition
fun higherfunc(addfunction:(Int,Int)-> Int){
// invoke regular function using local name
var result = addfunction(3,6)
print("The Addition of a and b numbers is: $result")
}
fun main(args: Array<String>) {
// invoke higher-order function
higherfunc(::addTwoNumbers)
}
Returning a function from Higher-Order function
While returning the function, we have to specify the parameter types and return type of
regular function in the return type of the higher-order function.
// function declaration
fun addition(a: Int, b: Int): Int{
return a*b
}//higher-order function declaration
fun higherfunc() : ((Int,Int)-> Int){
// ::addition return addition() function reference
return ::addition
}
fun main(args: Array<String>) {
// invoke function and store the return function into a variable
val sumOfTwoNumber = higherfunc()
// invokes the addition() function by passing 2,4 arguments
val result = sumOfTwoNumber(2,4)
println("The addition of two numbers is: $result")
}
Advantages of Using Higher Order Functions
· Higher Order functions helps reduce the code redundancy by allowing the common
code functionality to be passed as a function to another function.
· Increases readability of the code.
Solid Principles
https://www.educative.io/answers/what-are-the-solid-principles-in-java
Sealed classes
Sealed classes are a Kotlin feature that restricts the class hierarchy. This means that all direct subclasses of a sealed class must be declared within the same file or module. This can be used to improve the safety and readability of your code.
For example, you could use a sealed class to represent the different types of errors that can occur in your application. This would ensure that any code that handles errors can only handle one of the known types of errors, which can help to prevent bugs.
Sealed classes are also useful for implementing state machines. For example, you could use a sealed class to represent the different states of a game, and then use a when expression to switch between the states.
To define a sealed class, simply add the sealed modifier to the class declaration. For example:
map, filter, and reduce functions
· the map function takes a collection and a function as arguments, and returns a new
collection where each element has been transformed by the function
val strings = listOf("hello", "world")
val uppercasedStrings = strings.map { it.toUpperCase() }
· The filter function takes a collection and a predicate as arguments, and returns a
new collection containing only the elements that match the predicate
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
· The reduce function takes a collection and a function as arguments, and returns a
single value that is the result of applying the function to all of the elements in the
collection.
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, i -> acc + i }
Structured concurrency
· “Structured concurrency” refers to a way to structure async/concurrent computations
so that child operations are guaranteed to complete before their parents.
· It is based on the idea of coroutines, This means that coroutines cannot interfere with
each other
· Coroutines do not need to be explicitly synchronized, and they can share resources
without causing deadlocks.
Kotlin extension functions
Kotlin extension functions are functions that are defined outside of a class, but can be called
as if they were members of that class. This allows you to add new functionality to existing
classes without the need for inheritance or modifying the original class.
fun String.reverse(): String {
return this.reversed()
}
fun String.addExclamation(): String {
return "$this!"
}
val reversedString = "Hello, world!".reverse()
val message = "Hello".addExclamation()
infix function
An infix function is used to call the function without using any bracket or parenthesis. You need to use the infix keyword to use the infix function.
Kotlin Flow
A flow in Kotlin coroutines is a cold asynchronous data stream that emits values sequentially and it can complete normally or with an exception. It is similar to a Sequence, but it is lazy, meaning that it does not start emitting values until it is collected. Flows are also cancelable, meaning that you can cancel the emission of values at any time.
Here are some of the benefits of using Kotlin Flows:
· They are asynchronous, meaning that they can be used to process data in parallel.
· They are lazy, meaning that they do not start emitting values until they are collected.
· They are cancelable, meaning that you can cancel the emission of values at anytime.
· They are easy to use, and they can be used to implement a variety of data processing tasks.
Sequence
· A sequence in Kotlin is a synchronous data structure and is a lazy, potentially infinite
collection of elements that can be processed sequentially.
· Sequences are similar to collections, but they have some important differences.
- First, sequences are not stored in memory, they are generated on the fly. This makes them ideal for processing large data sets that would not fit into memory.
- Second, sequences can be processed lazily, which means that the elements are not evaluated until they are needed. This can improve performance for large data sets.
typealias
typealias is used to create an alternative name or alias for an existing type. It allows you to
define your own custom type names that can make your code more readable and expressive.
The typealias does not create a new type; it simply provides a new name for an existing type.
tail recursion
in tail recursion, we perform the calculation first, and then we execute the recursive call,
passing the results of the current step to the next recursive call
by Keyword
The by keyword in Kotlin is used for delegation. It allows one object to delegate a property or a
function call to another object. The purpose is to simplify code by reusing existing
implementations or adding extra behavior to the delegated object.
init and constructor
init is an initialization block that is executed when an instance of a class is created, difference
is that the init block is always executed regardless of which constructor is used
operator
The operator modifier in Kotlin is used to overload or define custom behavior for operators. It
allows you to provide custom implementations for built-in operators such as +, -, *, /, ==, !=,
etc. By using the operator modifier, you can define how your objects should behave when
operated upon with specific operators
function types
Function types in Kotlin allow you to define types for functions. They specify the signature of a
function, including the parameter types and return type. Function types can be used as
parameter types, return types, or variable types. You can define function types using the
syntax (parameters) -> returnType.
Property access syntax
Property access syntax in Kotlin allows you to define custom behavior for property access and
assignment. It provides a way to customize the logic when getting or setting a property value
Closure
a closure refers to a function that can access variables and parameters from its surrounding
scope, even after the scope has finished execution. It captures the variables it needs, stores
them, and can access them later when the function is invoked. The captured variables
maintain their state, and any modifications made to them within the closure will be preserved
function composition
Function composition in Kotlin refers to combining multiple functions to create a new function
that performs a series of transformations or computations. It allows you to chain functions
together, where the output of one function becomes the input of the next function. Function
composition promotes modularity, reusability, and readability of code by breaking down
complex operations into smaller, reusable functions.
requireNotNull
The requireNotNull function in Kotlin is used to check whether a given value is not null. It
throws an IllegalArgumentException if the value is null and returns the non-null value
otherwise
top-level functions
Top-level functions in Kotlin are functions that are declared outside of any class or interface.
They are defined at the top level of a file, making them accessible from any part of that file and
any other files in the same module. Top-level functions provide a way to organize and
encapsulate related logic that doesn’t belong to a specific class.
pair and triple
Pair and Triples are used to return two and three values respectively from a function and the
returned values can be of the same data type or different.
labels
We can create a label by using an identifier followed by the @ sign. For example, name@,
loop@, xyz@, etc
Sealed Class over Enum
Sealed classes give us the flexibility of having different types of subclasses and also
containing the state. The important point to be noted here is the subclasses that are extending
the Sealed classes should be either nested classes of the Sealed class or should be declared
in the same file as that of the Sealed class.
Jetpack Compose
Jetpack Compose is a modern toolkit for building native UI on Android. It can speed up
development and reduce errors by reducing the amount of boilerplate code required. Jetpack
Compose also offers these benefits:
· Shorter, more expressive code
· Single code base for writing code
· Easier view building and animation
· Lower technological debt
· Composable functions for easy composition and reusability of UI components
· More modular and maintainable codebases
Jetpack Compose architecture
The architecture components are Room, WorkManager, Lifecycle, Navigation, Paging, Data Binding,
ViewModel, LiveData.
Traditional Android View system and the Jetpack Compose UI toolkit
The traditional Android View system uses XML layouts and imperative programming to create
and manage UI components. Jetpack Compose is a declarative UI toolkit that uses Kotlin and powerful
tools to build native Android UI.
Here are some differences between the traditional Android View system and Jetpack Compose:
Layouts
The traditional Android View system uses XML layouts, which can lead to complex view hierarchies and
performance issues. Jetpack Compose uses a declarative approach where UI components are described
as functions of the application state.
Code
Jetpack Compose uses less code than the traditional Android View system. For example, one
partner said that the code for a button class was 10 times smaller.
Language
Jetpack Compose is written entirely in Kotlin. The traditional Android View system uses XML for
layout, style, typography, color, and other UI-related elements.
Function-based
Jetpack Compose uses a function-based approach. The naming convention is starting with a
capital letter like a class name.
Benefits
Jetpack Compose offers live preview and interactive development, native performance, and
seamless animations and transitions.
Life cycle of the Compose
The lifecycle of a composable in Jetpack Compose has three stages: Composition, Recomposition,
Uncomposition (Removal)
Junit
JUnit is a testing framework that can be used to test code. JUnit is an open-source software testing
framework for Java, including annotations, assertions, and rules for organizing and running tests
· It allows developers to write tests in Java and run them on the Java platform.
· JUnit is used to write and run repeatable automated tests.
· It has a built-in reporter that can print out the results of the tests.
JUnit is designed to work best with a number of small tests. It can be used to:
· Test early and automate testing
· Compile tests with the build so that regression testing can be done
· Allow test code re-usage
Unit Testing
Unit testing is a software development process that involves testing the smallest testable parts of an
application, called units. The purpose of unit testing is to ensure that each unit of the software works as
intended and meets the requirements
JUnit annotations
JUnit annotations are a special form of metadata that can be added to Java source code to improve
readability and structure. They provide extra information about classes and methods in the code.
Some of the most commonly used JUnit annotations are:
· @Test: Used to create simple unit tests
· @Before: Executes a method before all tests
· @AfterClass: Executes tasks after all tests have been completed
· @Disabled: Prevents @Test methods from running
· @Tag: Used to group tests into categories
public class MyTestCase extends TestCase {
@Test
public void testAdd() {
int expected = 5;
int actual = 2 + 3;
assertEquals(expected, actual);
}
}
MVVM Architecture
Refer: https://talent500.co/blog/mvvm-interview-questions/
The MVVM (Model-View-ViewModel) architecture is a popular design pattern used in software
development for creating user interfaces. It is particularly common in frameworks such as Flutter,
Xamarin, and Angular, and is widely used for building applications for desktop, mobile, and web
platforms.
MVVM consists of three main components the Model, the View, and the ViewModel.
Model- It represents the business and data logic. It’s responsible for retrieving and storing data
and communicating with external data sources such as databases or APIs.
View- It represents the user interface of the application. It is responsible for displaying the data
to the user and receiving user input. The View interacts with the ViewModel to bind data and
commands, and it may also trigger events or callbacks based on user interactions.ViewModel- It acts as an intermediary between the Model and the View. The ViewModel is
responsible for preparing the data to be displayed in the View, handling user input, and updating
the Model as needed. It encapsulates the business logic and provides an abstraction layer
between the Model and the View, allowing for the separation of concerns.
Advantages of MVVM Architecture
Separation of concernsIt enforces a clear separation between the View, ViewModel, and Model, which makes the code
easier to understand, maintain, and test.
TestabilitySince the business logic is encapsulated in the ViewModel, it can be easily unit tested without
requiring a user interface.
FlexibilityAllows a high degree of flexibility in designing user interfaces, as the View and ViewModel can
be easily replaced or modified without affecting the Model.
Data bindingMVVM makes use of data binding, which allows for automatic synchronization of data between
the View and the ViewModel, reducing the need for manual updates and event handling.
· Enhance the reusability of code.
· All modules are independent which improves the testability of each layer.
· Makes project files maintainable and easy to make changes.
Disadvantages of MVVM Architecture
· This design pattern is not ideal for small projects.
· If the data binding logic is too complex, the application debug will be a little harder.
Difference Between MVC, MVP and MVVM Architecture Patterns in
Android?
Room Database
Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the
full power of SQLite. Room has three main components and those are Entity, Dao, Database
Why use Room?
· Compile-time verification of SQL queries. each @Query and @Entity is checked at the
compile time, that preserves your app from crash issues at runtime and not only it checks the
only syntax, but also missing tables.
· Boilerplate code
· Easily integrated with other Architecture components (like LiveData)
Difference between SQLite and Room persistence library:
· In the case of SQLite, there is no compile-time verification of raw SQLite queries. But in
Room, there is SQL validation at compile time.
· You need to use lots of boilerplate code to convert between SQL queries and Java data
objects. But Room maps our database objects to Java Object without boilerplate code.
· As your schema changes, you need to update the affected SQL queries manually. Room
solves this problem.
· Room is built to work with LiveData and RxJava for data observation, while SQLite does not.
Dependency Injection
Dependency injection is a pattern where dependencies are passed into a class from an external entity.
Injecting dependencies into a class allows for greater reusability of that class.
Dagger
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification
Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are:
@Module This annotation is used over the class which is used to construct objects and provide
the dependencies.
@Provides This is used over the method in the module class that will return the object.
@Inject This is used over the fields, constructor, or method and indicate that dependencies
are requested.
@ComponentThis is used over a component interface which acts as a bridge between @Module and
@Inject. (Module class doesn’t provide dependency directly to requesting class, it uses
component interface)
@Singleton This is used to indicate only a single instance of dependency object is created.
Dagger-Hilt
Dagger Hilt provides a smooth dependency injection way in androidIt reduces various steps in
comparison with Dagger2 and providing the better features so definitely we should learn Dagger-hilt to
use this advanced cutting-edge tool in dependency Injection.@HiltAndroidApp: Annotation which is required to keep top of the Android Application class@AndroidEntryPoint: This annotation is required to keep top of the Activity class.
@Inject: This annotation is required to inject field or constructor like repository, services etc.@HiltViewModel: This is class level annotation that need to keep top of the view model class.@Module: This is annotation that is require to keep top of the module object class.@InstallIn: This annotation is required to set up the module with component like Singleton Component.@Provides: This annotation requires to return feature of each module method.@Binds: This annotation requires to return feature of each module method but here module class must
be abstract
RxJava
observable sequences. It’s main building blocks are triple O’s, Operator, Observer, and Observables.
And using them we perform asynchronous tasks in our project. It makes multithreading very easy in our
project. It helps us to decide on which thread we want to run the task.
Zip: this is an operator to combine the result of multiple different API calls and return a single response.
- It is fully backward compatible so in your code, you do not need to write if-elsefor checking the Android version.
- Support for one-time and periodic tasks
- Ability to define constraints for task execution, such as network availability or device charging status
- Guaranteed task execution, even across device reboots
- Seamless integration with other Jetpack components, such as LiveData and ViewM
Picasso vs Glide
ProGuard
ProGuard is a free Java tool in Android, which helps us to do the following
- Shrink(Minify) the code: Remove unused code in the project.
- Obfuscate the code: Rename the names of class, fields, etc.
- Optimize the code: Do things like inlining the functions.
In short, ProGuard makes the following impact on our project,
- It reduces the size of the application.It removes the unused classes and methods that contribute to the 64K method count limit of an Android
- application.
- It makes the application difficult to reverse engineer by obfuscating the code.
Android Architecture
The main components of the Android architecture are Applications, Application Framework,
Android Runtime, Platform Libraries, Linux Kernel
Core building blocks
the activity comes to the foreground, or onStop() if it becomes hidden.
at the top of the activity stack, with user input going to it.
not (yet) been killed.
onCreate() vs onStart()
- The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated, for example during a configuration change.
- The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().
Fragment LifeCycle
change occurs. Calling setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle,
signaling the system to retain the current instance of the fragment when the activity is recreated.
Foreground Service: A foreground service performs some operation that is noticeable to the user.
For example, we can use a foreground service to play an audio track. A Notification must be
displayed to the user.
Background Service: A background service performs an operation that isn’t directly noticed by the
user. In Android API level 26 and above, there are restrictions to using background services and it
is recommended to use WorkManager in these cases.
Bound Service: A service is bound when an application component binds to it by calling bindService()A bound service offers a client-server interface that allows components to interact with the service,
send requests, and receive results. A bound service runs only as long as another application component
is bound to it.
LocalBroadcastReceiver
This a broadcastreceiver which is used for updating the UI from a background service. We need to
register a LocalBroadcastReceiver in the activity. And send a broadcast with the data using intents
from the background service. As long as the activity is in the foreground, the UI will be updated from
the background. Ensure to unregister the broadcast receiver in the onStop() method of the activity
to avoid memory leaks
Launch Modes
Standard (Default)
Each time an activity is launched, a new instance of the activity is created on top of the activity stack. If the activity already exists in the stack, still, a new instance will be created on top of it
SingleTop
if the activity is already at the top of the stack, a new instance will not be created. Instead, the onNewIntent()
method of the existing instance will be called with the new intent, if the activity is not at the top of the
stack, a new instance will be created on top of the stack.
SingleTask
If there are no existing instances of the activity in the task, a new instance is created. If there is an existing instance of the activity at the top of the task, the system will pass the intent data
to the onNewIntent() method of that existing instance. If there is an existing instance of the activity in the
task but not at the top, the task is brought to the foreground, and all the activities above the singleTask
activity in the stack are cleared or destroyed.
SingleInstance
In SingleInstance launch mode, it creates a new task and ensures that no other activities (even from different
applications) are placed in the same task. The SingleInstance activity is always placed in a new task and is isolated from the rest of the
application and other tasks.
1. Standard. 2. SingleTop
3. SingleTask 4. SingleInstance
commit() vs apply() in SharedPreferences
commit() writes the data synchronously and returns a boolean value of success or failure depending on the result
immediately.
apply() is asynchronous and it won’t return any boolean response. Also if there is an apply() outstanding and
we perform another commit(). The commit() will be blocked until the apply() is not completed.
RecyclerView
It is designed to display long lists (or grids) of items, RecyclerView instead creates only the visible number count views that are on screen, this will speed
up the loading and memory usage. While scrolling instead of creating a new view for each new row, an old view is recycled and reused
by binding new data to it and this happens in onBindViewHolder()
RecyclerView vs ListView
· ViewHolder Pattern: Recyclerview implements the ViewHolders pattern whereas it is not mandatory in a ListView.
A RecyclerView recycles and reuses cells when scrolling.
· What is a ViewHolder Pattern? — A ViewHolder object stores each of the component views inside the tag field of the Layout,
so you can immediately access them without the need to look them up repeatedly. In ListView,
the code might call findViewById() frequently during the scrolling of ListView, which can slow
down performance. Even when the Adapter returns an inflated view for recycling, you still need
to look up the elements and update them. A way around repeated use of findViewById() is to use the "view holder" design pattern.
· LayoutManager: In a ListView, the only type of view available is the vertical ListView. A RecyclerView
decouples list from its container so we can put list items easily at run time in the different
containers (linearLayout, gridLayout) by setting LayoutManager.
· Item Animator: ListViews are lacking in support of good animations, but the RecyclerView brings a whole
new dimension to it.
JobScheduler
The JobSchedular API is used for scheduling different types of jobs against the framework that will be
executed in your app’s own process. This allows your application to perform the given task while being
considerate of the device’s battery at the cost of timing control.
The JobScheduler supports batch scheduling of jobs. The Android system can combine jobs for reducing
battery consumption. JobManager automatically handles the network unreliability so it makes handling
uploads easier.
Here are some examples of a situation where you would use this job scheduler:
· Tasks that should be done when the device is connected to a power supply.
· Tasks that require a Wi-Fi connection or network access.
· Tasks should run on a regular basis as a batch where the timing is not critical.
No comments:
Post a Comment