A Brief Introduction to Coroutines With Example

A Brief Introduction to Coroutines With Example

Software engineers have to address some problems that are common within an application under development. They use design patterns such as Singleton and various other design patterns. Similarly, there are design patterns for concurrency as well. Coroutines is one such design pattern used in Android development. This design pattern is for simplification of code that is executed asynchronously. Coroutines were introduced in Kotlin in version 1.3. They are based on concepts from other programming languages. 

There can be multiple tasks (threads) running at the same time on Android. An app becomes unresponsive when a long-running task blocks the main task. Coroutines help in managing such long-running tasks. Over 50% of Android developers enjoy increased productivity with coroutines. This design pattern facilitates cleaner and concise code.


Coroutines 

The word ‘Coroutines’ is a combination of ‘Co’ and ‘Routines’. Here:

  • Co means cooperation   
  • Routines means functions

Coroutines means cooperation between functions. 

Coroutines functions

Consider the following code as an example. In this code, we use two functions including functionA and functionB.   

functionA as below:

fun functionA(case: Int) {

    when (case) {

        1 -> {

            taskA1()

            functionB(1)

        }

        2 -> {

            taskA2()

            functionB(2)

        }

        3 -> {

            taskA3()

            functionB(3)

        }

        4 -> {

            taskA4()

            functionB(4)

        }

    }

}

And functionB as below:

fun functionB(case: Int) {

    when (case) {

        1 -> {

            taskB1()

            functionA(2)

        }

        2 -> {

            taskB2()

            functionA(3)

        }

        3 -> {

            taskB3()

            functionA(4)

        }

        4 -> {

            taskB4()

        }

    }

}

Call the functionA as functionA(1). The functionA will execute taskA1 and functionB gets control for the execution of the taskB1. After the completion of the taskB1, the functionB will give control to the functionA for the execution of taskA2 and so on.   

As you can see in the code that both functions cooperate. Kotlin coroutines makes this cooperation easy without using when or switch case as you can see in the given example. 

This example shows that coroutines make multitasking much easier. Both the threads and coroutines are multitasking. The difference is that coroutines are controlled by the developer and threads are managed by the operating system. Developers use coroutines to execute a few lines of code. 

The cooperative nature of functions makes this framework written over actual threading light and yet powerful. Coroutines are lightweight and faster threads. They don’t require context switching as they don’t map on the native thread.

Features 

App developers are recommended to use coroutines for asynchronous programming. The following are key features:

ey features:    

  • Lightweight   

The support for suspension allows you to run multiple coroutines on single thread. Suspension does not block a thread on which coroutine is running. This supports multiple concurrent operations and at the same time, saves memory.

  • Built-in Support for Cancellation   

It automatically propagates cancellation through the running coroutine hierarchy. 

  • Fewer Memory Leaks

It allows running operations within a scope using structured concurrency. 

  • Jetpack Integration

Extensions included in Jetpack libraries provide full support for coroutines. You can also use coroutine scope provided by some libraries for structured concurrency.

Let’s understand this with a real life example.

Imagine you have to parse data from 100 sites. It requires making a call for each of the 100 sites. After you receive the response, you do something with the data received from 100 sites. You can start 20 threads with multithreading in a pool. Each thread uses memory, sends a request before sleeping. After finishing, some threads return to the pool and make another call before sleeping only. As you can see, you are making all 100 calls simultaneously in one thread. 


Dependency Info 

You need to add the following dependency to the build.gradle file of the app to use coroutines in an app under development: 

dependencies {

    implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9’

}

What’s New in Bootstrap 5 Alpha

What’s New in Bootstrap 5 Alpha

What’s New in Bootstrap 5 Alpha 

Bootstrap is a CSS framework that makes responsive web and mobile development fast and easy. Bootstrap provides you with HTML and CSS based templates for forms, typography, tables, buttons, modals, navigation, image carousels and more. In this article, we will explore the latest Bootstrap 5 alpha version.

 

Modified grid system 

The grid system is one of the main attractions of Bootstrap. This system is made more capable in Bootstrap 5 alpha version. It comes with an extra extra large grid (xxl). This version has .g* utilities in the place of .gutter classes. You will also find Vertical spacing classes.

code

Let’s see an example.
As you can see in the image, g-4 is spacing of 20px (1.5rem) from all side. You can also use .gy* and .gx* to give it specifically for horizontal and vertical.
.gy* is for vertical gutter spacing
.gx* is for horizontal gutter spacing
Columns are not position:relative by default anymore. The new grid system has replaced form layout options. Bootstrap 5 alpha container comes with 6 breaking points.
Xs <= 576px
Sm >= 576px
Md >= 768px
Lg >= 992px
Xl >= 1200px
Xxl >= 1440px
The grid system is greatly enhanced.

Column
Column
Column
Column

Updated forms

The Forms Section is a separate section in Bootstrap 5 alpha. All form controls are redesigned and deduped. Form controls are now fully custom. Every radio, checkbox, file, select, range etc come with a custom appearance. You can unify the behaviour and style of form controls across browsers and operating systems.

settings

Customizing docs

 

Many libraries have been created based on Bootstrap. The latest version provides more support to extend Bootstrap, thanks to the new Customization Section. This section comes with more code snippets and content to build on top of source Sass files of Bootstrap. You also get an npm starter project.

 

CSS custom properties

 

Before Bootstrap 5 alpha, a limited set of root variables for fonts and colours had CSS custom properties. In the Bootstrap 5 version, you get them in components and layout options also.

 

No More jQuery

The largest change in the latest version is no jQuery. It is replaced with Vanilla JavaScript.

 

Responsive Font Size

Font size and margin padding are automatically adjusted across device and viewport sizes.
Eg: .class {
Padding : rfs(2rem);
}
It no longer supports Internet Explorer. There are many new icons added to Boostrap 5. However, you will not find any social media icons.

Following are the classes removed and added:
Classes Added:

 

  • row-cols-auto
  • g-*
  • gy-*
  • gx-*

Classes Removed

 

  • Form-row
  • Card-deck
  • Form-inline
  • List line

 

The latest version of Bootstrap 5 brings utilities API:

Angular MVVM architecture
Angular MVC Architecture: Angular App

Angular MVC Architecture: Angular App

MVC Architecture 

Model View Controller or MVC architecture is one of the design patterns used in the development of web applications. The MVC design pattern separates model, view and controller. 

Model 

It supports application data management. Model receives requests from view and instructions from controller and then updates itself accordingly.  

View 

View is a user interface that displays data and also allows the user to modify data. 

Controller 

Controller controls the model-views relationship. It receives user input, performs validations and then modifies data after performing business operations. 

MVVM Architecture 

MVVM is another software design pattern that improves source code readability and maintainability. It divides the code into three sections including: 

  • Model 
  • View 
  • ViewModel 

 

ViewModel 

It exposes data to the view after receiving from Model. 

Let’s talk about both MVC and MVVM approaches.

 

Architecture Blueprint

Angular MVVM architecture

Model

The model part of the MVC architecture consists of the business end of the application. It is a simple data for CRUD applications. You can see the model holding data in the following example:

Example

import { Injectable } from ‘@angular/core’;

import { BehaviorSubject, Observer } from ‘rxjs’;

export class Note {

  id: number;

  title: string;

  text: string;

}

@Injectable({

  providedIn: ‘root’

})

export class NotesService {

  private notes: Note[];

  private nextId = 0;

  private notesSubject = new BehaviorSubject<NoteInfo[]>([]);

  constructor() {

    this.notes = JSON.parse(localStorage.getItem(‘notes’)) || [];

    for (const note of this.notes) {

      if (note.id >= this.nextId) this.nextId = note.id+1;

    }

    this.update();

}

  subscribe(observer: Observer<NoteInfo[]>) {

    this.notesSubject.subscribe(observer);

  }

  addNote(title: string, text: string): Note {

    const note = {id: this.nextId++, title, text};

    this.notes.push(note);

    this.update();

    return note;

  }

}

export class Note{

id:number,

title:string,

text:string
}

The model in this example holds an array of text nodes.

View

The view is created in .html templates and .css files. One of these templates is already mentioned in src/app/app.component.html.


ViewModel/Controller

The ViewModel/Controller is created in the .ts files. Open src/app/app.component.ts

 

How to Install

Open terminal and run the following commands to install Angular CLI and set up your application.

  • npm install -g @angular/cli@7.2.1
  • ng new AppName
  • cd AppName
  • ng serve

AngularCLI

 Inputdecorator The following table shows some of the common Angular commands: 

Creating a component ng generate component component_name
Creating a service ng generate service service_name
Creating a module ng generate module module_name
Creating a directive ng generate directive directive_name

 

Click the link below to learn about all generate commands:
https://angular.io/cli/generate

 

Data Sharing

Data Sharing Between Components

Parent to Child

You can use @Input decorator .[] for parent to child data sharing. This is known as property binding.

Inputdecorator

Child to Parent

You can use @Output decorator for child to parent data sharing.

Data Sharing Between Unrelated Component

Use services to store data and make HTTP calls to retrieve, post, update and delete data.

Lazy Loading in Angular

Take the following steps for lazy loading in angular:

Step 1: Create a Module

Create one more module file with the name Lazy for loading on demand. Use the following command:

ng g module Lazy

Create one component file with the name employee. Use the following command:

ng g component Lazy/employee

Step 2: Add Lazy Loading Module 

  • Open app.routing.ts file
  • Import Routes
  • Import RouterModule from @angular/router

Add the following code snippet in the app-routing.module.ts file.

 

Step 3: Add Routing of Lazy Module Component

  • Open lazy.module.ts file
  • Define components in routes
  • Use RouterModule.forchild with your child routes array

Use the following code snippet for lazy.module.ts file.

ModuleComponent

Step 4: Add Lazy Loading Module

  • Open app.module.ts file
  • Import AppRoutingModule

This is how the code will look like:

LoadingModule

And also add

Import {LazyModule} from ‘./lazy/lazy.module ;

Import:[

BrowserModule,

AppRoutingModule,

LazyModule

]

Android MVP Architecture: Android App

Android MVP Architecture: Android App

When you start learning coding to be a software developer, website developer, Android or iOS developer, your coding journey begins with simple programs for adding or subtracting two numbers, leap year, fibonacci series and then you move onto some small real world applications such as banking application with the three basic operations for balance enquiry, deposit and withdrawal.

Collecting user input, storing the input values in variables, defining methods/functions with proper validations and displaying the output, everything is covered in a single program.

However, desktop apps, web apps and mobile phone apps used by businesses are much more complex. Developing optimized apps easily is not possible without separating different layers of code. You cannot manage it if your code is not modular. It becomes difficult to update the app or add new features. This is the reason why you need an architecture for Android app development.

If you are a beginner, you should start with the MVP architecture.

MVP Architecture


MVP (model-view-presenter) is an architectural pattern that promotes separation of concerns and facilitates unit testing. This architecture has the following three components:

 

  1.  Model (interactor, REST API, database API)
  2. Presenter
  3. View (activity, fragment, view)

 

Model

It is the data store of the app. The model layer includes Shared Preferences, SQLite databases, and repositories for network calls. Model provides the data to be displayed in your app. API calls in the activity class are no longer needed. They are separated in the model and results can be retrieved from there.

 

View

It consists of fragments, activities and other views. The view is what you see on your screen. The data come from the presenter and populated into the views on the screen. 

 

Presenter

The presenter makes API calls, fetches data from files or databases, replaces fragments, fetches data from sharedpreferences, starts new activities and performs other similar tasks. The presenter contains the business logic. 

The following are the features of MVP architecture:

  • Separation of concerns
  • Easier to debug
  • Reusability
  • Unit/integration testing
  • Scalability

Now, let’s see the implementation of MVP architecture with an Android app using Dagger2, RxJava, GreenDao, PlaceHolderView, FastAndroidNetworking and AndroidDebugDatabase.

 

Architecture Blueprint 

ArchitectureBlueprint

Project Structure

ProjectStructure

The app has the following packages:

  • data package contains all the components that access and manipulate data.
  • di package contains classes that provide dependency using Dagger2
  • ui package contains view classes and corresponding presenters
  • service package contains services for the app.
  • utils package contains utility classes.

Classes in the app use key OOP features like inheritance and facilitate code reusability.

 

Library reference resources

Dagger2

https://github.com/MindorksOpenSource/android-dagger2-examplehttps://github.com/MindorksOpenSource/android-dagger2-example

RxJava2

https://github.com/amitshekhariitbhu/RxJava2-Android-Samples

ButterKnife

http://jakewharton.github.io/butterknife/ 

FastAndroidNetworking

https://github.com/amitshekhariitbhu/Fast-Android-Networking 

GreenDao

http://greenrobot.org/greendao/ 

PlaceHolderView

https://github.com/janishar/PlaceHolderView 

Calligraphy

https://github.com/chrisjenx/Calligraphy 

AndroidDebugDatabase

https://github.com/amitshekhariitbhu/Android-Debug-Database 

 

Concept reference resources: 

  1. Introduction to Dagger 2: Part 1
  2. Introduction to Dagger 2: Part 2
  3. Android Dagger2: Critical things to know before you implement
  4. The Best Android Networking Library for Fast and Easy Networking
  5. RxJava + Fast Android Networking
  6. Migrating from RxJava 1.0 to RxJava 2.0 and Learn RxJava by Examples
  7. Android Tinder Swipe View Example
  8. Debugging Android Databases And Shared Preferences In The Easiest Way
  9. RxJava Anatomy: What is RxJava, how RxJava is designed, and how RxJava works.
  10. Powerful Android ORM: greenDAO 3 Tutorial


MVP template
 

When you are following architecture patterns like MVP, MVP clean or MVVM, this involves creation of basic files like API models, View, Presenter, and Android Activity and then boiler plate code. You have to spend 1-2 hours on each screen. You can use an automated template to save time and ease out work.

 

How to Install 

Find and paste the MVPActivity folder under the root directory of android-mvp-architecture app at the below location:

C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities 

Restart the Android Studio. 

AndroidStudio

How to Use

 

Select the folder in which you want to create the new MVP folder. The following will be created in the new folder: 

  • View class
  • MVpPresenter 
  • Presenter 
  • Activity

 

How to use template
A Simple Guide to Basic GIT Commands

A Simple Guide to Basic GIT Commands

Ada Lovelace, a young visionary mathematician wrote the first computer program for Charles Babbage’s Analytical Engine to calculate a sequence of Bernoulli numbers. She predicted that by representing data into numbers, machines (modern computers) could produce graphics,  compose music and be useful to science. What she predicted more than 150 years ago is actually happening. It all started with her program.

Today programmers are writing way more complicated computer programs and software applications. Teams of developers collaborate to develop mobile apps, desktop apps and web apps that are running businesses. 

However, multiple programmers writing code for the same application can lead to inconsistency and errors without proper collaboration and version control. This is the reason why code collaboration and version control platforms play a significant role in the development of software applications. SVN, GIT and there are several other version control systems. However, GIT is the most used tool for source code management and tracking changes in files. GITHUB is another tool that is very popular in the software/web development industry. 

GIT and GITHUB are not the same. However, they are closely connected. GIT is a version control system. You have to install and maintain GIT on your local system. It provides you with the branching model. You can create an independent branch and try out new ideas. It takes a click of a button to delete, merge, and recall branches.  

On the other hand, GITHUB is a cloud-based hosting service that is designed as a GIT repository hosting service. It allows you to share code with others. You can revise or edit your code.

 

To use GIT and GITHUB, install git and create a GitHub account. To create a new project on your computer, create a new repository. First of all, open the terminal and move to the folder to place the project. 

$ cd ~/Desktop

$ mkdir myproject 

$ cd myproject/

Now, run git init command to initialize a git repository.

$ git init

Once you see the following in the terminal, you can add a new file to repo:

Initialized empty Git repository in /………………./Desktop/myproject/.git/

Adding a new file to the repo:

You can use touch command to add a new file to the repository.

$ touch filename.txt

Use the git status command to see the files in the repo:

$ git status

If you want to upload a file from your computer, open the terminal and use the following commands:

$ git config –global user.name “ADD_YOUR_USERNAME”
$ git config –global user.email “ADD_YOUR_EMAIL”

Clone GIT repository

$ git clone GIT_REPO_LINK
$ cd FOLDER_NAME
$ touch README.md
$ git add README.md
$ git commit -m “add README”
$ git push -u origin master

You can also push an existing folder using the following commands:
Move to the existing folder.

$ cd existing_folder

 

 

 

 

 

 Now run the following commands in the terminal:

$ git init
$ git remote add originGIT_REPO_LINK
$ git add .
$ git commit -m “Initial commit” //ADD YOUR COMMENT HERE
$ git push -u origin master

You can push an existing repository using the following commands:
Move to the existing_repo

$ cd existing_repo

Use the following commands:

$ git remote rename origin old-origin
$ git remote add origin GIT_REPO_LINK
$ git push -u origin –all
$ git push -u origin –tags 

Switching Branches in GIT

Having more than one branch in the repository is pretty common. You can easily switch branches in GIT using checkout command. Suppose you have the following two branches in your repository:

  • master
  • hello-git-branch

Suppose that the master branch is the current branch. Run the following command to switch to hello-git-branch.

$git checkout hello-git-branch

In this demo, we transfer a remote repo to a local machine from Github. It contains the following two branches:

  • master branch
  • hello-git-branch

The hello-git-branch is created using:

$ git branch hello-git-branch

As you can see in the git bash screenshot, the current active branch is master branch:

You can see $ ls command returning the names of the files in the master branch.

 

Switching From master to hello-git-branch Branch   

Run the following command and check the change in the below screenshot:

 

$ git checkout hello-git-branch

 

You can see that no message is displayed. However, you can see the name of the branch ‘hello-git-branch’ in brackets.

 

 

gitignore File 

It is a file in which you can list certain files and folders that you want GIT to ignore. You can create this file both locally and globally. When created locally, it is often added to the project’s root directory. When created globally, all entries in the .gitignore file are ignored in all the Git repositories.

 

Creating a .gitignore File Locally

Create a text file with name ‘.gitignore’. Now add folder or file you want to be ignored. Keep in mind that you have to add one entry at each line.

The entries in the .gitignore can follow certain matching patterns. Check the table:  

 

 

* Wildcard Match 
/ Ignore pathnames
# Add comments

 

 .gitignore File Example 

# Ignore Mac system files
.DS_store

# Ignore node_modules folder
node_modules

# Ignore all text files
*.txt

# Ignore files related to API keys
.env

# Ignore SASS config files
.sass-cache

Run the following command to add or change the global .gitignore file:

$ git config –global core.excludesfile ~/.gitignore_global

This creates the file ~/.gitignore_global. Edit the global .gitignore file just like a local .gitignore file.
 

Untracking Files Committed from Gitignore 

 

You can untrack a single or every file in .gitignore.

The following command untracks a single file

$ git rm –cached filename

Untracking every file:

Commit all the outstanding changes in the code and run the following command:

$ git rm -r –cached

Now run:

$ git add .

Commit it:

$ git commit -m “.gitignore is now working”

You can use git add filename to undo git rm –cached filename.