ICSE – Mathematics

  1. Logarithms
  2. Integrations
  3. Derivatives
  4. Limits
  5. Probability

#Credit – NCERT

My Notes:

ICSE XI- Mathematics

Chapters: 16
Chapter1: Sets
Chapter2: Relations & functions
Chapter3: Trignometric functions
Chapter4: Principle of Mathematical Induction
Chapter5: Complex numbers and quadratic equations
Chapter6: Linear inequalities
Chapter7: Permutations & Combinations
Chapter8: Binomial theorem
Chapter9: Sequences & Series
Chapter10: Straight Lines
Chapter11: Conic sections
Chapter12: Introduction to the Three dimensional geometry
Chapter13: Limits & Derivatives
Chapter14: Mathematical reasoning
Chapter15: Statistics
Chapter16: Probability
Chapter17: Infinite Series
Chapter18: Mathematical modeling

Chapter1: Sets
. Theory of sets developed by German mathematician George Cantor(1845-1918) while working on ‘problems on trigonometric series’.
. A set is a well defined collection of objects.
. Sets are denoted by capital letter eg. A, Z, N etc
. Elements of set are denoted by small letter eg. a,b,c
. If a is an element of set A, then
. a belongs to A
. a ϵ A (epsilon – belongs to)
. If a is not an element of set A, then
. a does not belongs to A
. a ∉ A (epsilon not – not belongs to)
. Methods of representation
. Roster / tabular form
. set builder form
. Roster – all even number less than 7 => {2, 4, 6}
. Here order of elements are immaterial
. Same elements are not repeated
. Set builder – V = {x: x is even number and 0 < x < 7}

Q1) Write the solution set of the equation x^2 + x – 2 = 0 in roster form
A1) (x – 1)(x + 2) = 0 i.e. x = 1, – 2
therefore X= {1, -2}

Q2) Write the set {x: x is a positive integer and x^2 < 40} in the roaster form
A2) X = {1, 2, 3, 4, 5,6}

Q3) Write the set A = {1, 4, 9,16,25, …} in builder form
A3) {x: x is a square of natural numbers}
{x: x = n^2, where x ϵ N}

Q4) Write the set {1/2, 2/3, 3/4, 4/5, 5/6, 6/7} in the set builder form.
A4) X = {x: x = n / (n + 1) and n ϵ N and 1 <= n <= 6}

Q5) {P,R,I,N,C,A,L} = { x: x is letter of the word PRINCIPAL}
{0} = {x: x is an integer and x + 1 = 1}
{1,2,3,6,9,18} = {x : x is positive integer and is divisor of 18 }
{3, -3} = {x: x is an integer and x^2 + 9 = 0}

#2 – The empty set
. A set which does not contains any element is called the empty set or the null set or the void set.
. Empty set denoted by Ø or { }
. eg. A = {x: 1 < x < 2, x is natural number}
C = {x: x is an even prime number greater than 2}

#3 – Finite and infinite sets
. Finite set – A = {1,2,3,4} or W = {x: x is day of week}
. Infinite set – B = {men living presently in different part of world}
G = {x: x is point on line}
. A set which is empty or consists of a definite number of elements is called finite otherwise, the set is called infinite.
. Infinite set is written as ending with … eg {1,2,3,…}
. All infinite sets can not be described in the roaster form. (means few can be)
. eg set of real numbers can not be described in roaster form. (set which starts with … and ends …, can not be described in roaster form).

A6) {x: x ϵ N and (x-1)(x-2) = 0} => finite => {1,2}
{x: x ϵ N and x^2 = 4} => finite => {2}
{x: x ϵ N and 2x – 1 = 0} => finite => { }
{x: x ϵ N and x is prime} => Infinite => {1,2,3,5, …}
{x: x ϵ N and x is odd} => Infinite => {1,3,5,7, …}

#4 – Equal sets
. Two sets A and B are said to be equal if they have exactly the same elements and we write A = B. Otherwise, the sets are said to be unequal and we write A ≠ B.
. Equal : A = {1,2,3,4} B = {4,2,3,1} A = B
. Unequal : A = {-1,2,3,4} B = {4,2,3,1} A ≠ B
. A set does not change if an element is repeated
A = {1,2,3} and A={1,2,1,3} are same

A7) A={0}, B={x: x>15 and x<5} = { }, C={x: x-5 = 0 } = {5}
D={x: x^2 = 25} = {-5, 5} E={x: x is an integral positive root of the equation x^2 -2x -15 = 0} = {5}
: C=E

A8) X = {A,L,O,Y}, B = {L,O,Y,A} => X=B

A9)

How to visit Nandi hills Bangalore?

My family came 2 weeks ago to see me and I thought to take them any hill station in Bangalore. After search Nandi hill was the shortest available spot. I tried but could not succeed due to short time but there were many other factors who blocked the trip to be finalized or realised.

1. Very few hotels at top of Nandi hill. All booked before Friday for weekends.

2. There are no direct transportation available from any part of Banglore to Nandi hills. Train – you won’t reach there directly, station is far from there. Bus – No direct bus, multiple change. Cab – since it’s outstation to-fro charges will be applied and if you are night staying then price may go up.

So, I thought to try it alone and then take the family after knowing the location.

Here are few pointers,

1. Bus is hectic and need smart and researched approach. Most cheaper. Time consuming.

2. It’s around 60km from Bangalore and near to Kempegowda airport.

3. Hill station so in the morning and evening it would be cold, whatever be the month.

4. No ATM and carry cash. No Paytm, no Online transfer.

5. Government hotels krtc will not allow single person (u need to convince them, carry company id card). They will take 1000 cash as refundable deposit.

6. Sceneric place. Good maintained and very good for family.

7. All points within 2km circle max by walk. Battery car available for 10 points siteseen.

8. Best to come by bike or personal car.

9. Come early in the morning, go in the evening but not late, after sunset it’s dangerous and gate will be closed.

10. Hill top is secured with main gate which opens at 6am and closes at 6 pm. So if you are not staying at hill top then u won’t be able to enter it and go to sunrise point before 6am. Entry fees ₹20 per person plus car entry fees extra.

11. Last not least, book good room for avg 2k, cheaper 1k is good for bachelors or single not good for family..Specially government one.

Now, I will describe how I did it. Cab was easy mode but being alone I thought not good to spend 10k for single night trip. I researched on quora and google, found few good tips but still those were not sufficient.

Itinerary for Nandi hill from Bangalore

Places : Majestic or Kempegowda bus station, Devenhalli RTO corner, Chikkaballapur, Nandi or Nandigram, Nandi hill signal, Nandi hill top.

Some people will suggest to go to Chikkaballapur then take bus. Well I had issue here, from Chikkaballapur to Nandi hill bus frequency is very less, minimum 2.5 hrs or may be more.

From Devenhalli RTO which is after Airport, there are 2 cross roads, one goes to Chikkaballaur and another Nandi hills and both are approximately same 20km. And from Chikkaballandur to Nandi hill is 25km..So if you go to CKR and come to NH it will be 45km ie extra 25km plus more time.

I took bus from Ecospace bellandur to Ibbelur then another to Majestic and it took around 1.5 hrs. AC bus approximately ₹80.

Then at Majestic Terminal 1, took bus at plateform 1 for Chikkaballapur (frequency good, 15-30 min) non AC and semi ST kind of for ₹64.

Got down at Chikkaballapur stand and took another bus for Nandi at plateform 15. Here I had language issue, none were able to speak hindi but what I understood that there were no direct bus at that time for Nandi hills and this one would be dropping me at Nandi or Nandi gram. And here I misunderstood Nandi as Nandihill signal.

So I got down at Nandi and fare was ₹9 and approximately 9km. Then I realised my mistake, asked one Auto guy who told me that bus just left for Chikkaballapur and will come after 90 minutes. Since it was 1.30pm, I was not in mood to take bus anymore and was cursing myself for not opting Devenhalli rto stop route. Asked auto for Nandi hills – ₹400 was first bet and after negotiation we finally settled for ₹300. But there was twist, 4 Bcom college girls who also waiting there for bus from last 2 hours were negotiating with same guy, seems they came with little money (may be to see serial shooting I think). Auto wala told me if I can share the auto he will charge me ₹250 only. ₹50 was not issue for me but I knew the pain of transportation specially when you have little money. I had done many in my odd days. So I took the auto but girls were missing, after 10 minutes search we found them. After 5 minutes ride one girl started the talk and we could spoke only in english. All were enjoying their time even in that situation – friends. I hardly understood anything, nothing. But their laughing, doing masti was reminding of my days with my school friends.

Well whole 5 hrs journey ended around 3pm. But here is my take if I want to do another bus ride or you.

1. Start at early around 6am. Take bus from Majestic.

2. Get down at Devenhalli RTO cross road.

3. Try to take bus upto Nandi hill or atleast Nandi signal. If not then try to get at the end of the road.

4. Nandi hill from Nandi signal is around 8km. Take auto may be ₹150-200 or sharing.

Waiting at Devanhalli RTO is better than going to Chikkaballapur. But there is direct bus to Nandi hills from Chikkaballapur and if you missed waiting time would be 2 hrs or more.

Enjoy, I will post my return journey experience later.

How to see all points, sunrise, source of water, basavana?

There is trail near to Mayura pine top Restaurant not hotel near to Nandi sagar hotel…Go down and you will see all.

Return journey:

I did checkout at 11am and walked to the main gate while seeing Amrut sarovar and Tipu summer. Took share auto at 11.50am, fare was ₹30. Reached Nandi hill cross or signal in 20 minutes. Had my mini lunch there, white rice, rasam and curd. At 12.55 took another private local bus to reach Karahalli cross and fare was ₹10 and reached there in next 6 minutes. Here boarded another local bus for Devenhalli in next 10 minutes and fare was ₹15 for 15 minutes ride. Once I reach at Devanhalli, I will get plenty of buses to Majestic. And yup got another bus in next few minutes… Total journey would be 2hr excluding gaps.

Optimal route : Majestic – Devanhalli bus stop or Devanhalli RTO cross – Karahalli cross – Nandi hill signal – Nandi hill… 😂 32 + 15 + 5 + 30 = ₹82 one way.

I covered this trip 1 night 2 days by bus and expenses were ₹2500 including all things, 😂😂. Next time I will come by Bike.

Here are few glimpse at Nandi hills

Batch file to start applications for ReactNative app development [VSC, Emulator etc]

If you are lazy like me, and wants to automate to start all applications related to ReactNative app development then here are life savior steps for it.

This happens when you start your laptop and you have to manually start VisualStudioCode and then go to Android Studio and starts Android AVD manager and then starts AVD.
I am lazy, I can’t do that every time, so my most favorite and always to help me is, batch file[well after 5 years of Mac, I am forced to use Windows for time being]

Steps:

  1. Create a file reactnativeStarter.bat file anywhere and copy following lines

start C:\Users\[YourUserName]\AppData\Local\Programs\"Microsoft VS Code"\Code.exe
emulator @[Your AVD NAMe] -netdelay none -netspeed full
exit

2. Save and click on it.

Note:

  1. Add “C:\Users\[Your User name]\AppData\Local\Android\Sdk\emulator” to Environment variable “Path”
  2. Add “C:\Users\yogesh.kalwar\AppData\Local\Android\Sdk\platform-tools” to Environment variable “Path”
  3. Add “C:\Users\yogesh.kalwar\AppData\Local\Android\Sdk\tools” to Environment variable “Path”
  4. If you do not know the name of available AVD use following command
    emulator -list-avds
  5. For VSC, if path is different then go to VSC launcher icon and right click and select properties, it will give you exact path and make sure you do not include Code.exe in double apostrophes.

That’s Done!!!

Enjoy, happy coding!!!

Step by step adding Native code to ReactNative apps – Java with JS

For beginning, we will add simple Toast functionalities to react native js code.

Prerequisite – You have installed all components like nodejs, Android sdk, react-nativecli. If not please refer to https://facebook.github.io/react-native/docs/getting-started

  1. Creating project first
  1. Go to your repository folder eg. [react-native-code-base]
  2. Type: react-native init NativeModulePackageExample
    This will create ReactNative project with name “NativeModulePackageExample”
    Inside this there will be two folders,
    android: android native code base
    ios: iOS native code base

B. Create Toast native code

  1. Inside “android/app/src/main/java/com/nativemodulepackageexample” create another package or folder named “toast” 
  2. Here, I used VisualStudioCode as IDE for development.
    1. Create module for toast
      1. Create java file in toast package – ToastModule.java
package com.nativemodulepackageexample;

import android.widget.Toast;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.Map;
import java.util.HashMap;

public class ToastModule extends ReactContextBaseJavaModule {
  private static ReactApplicationContext reactContext;

  private static final String DURATION_SHORT_KEY = “SHORT”;
  private static final String DURATION_LONG_KEY = “LONG”;

  ToastModule(ReactApplicationContext context) {
    super(context);
    reactContext = context;
  }

  /**
  * The purpose of this method is to return the string name of the NativeModule
  * which represents this class in JavaScript.
  * So here we will call this ToastExample so that we can access it through React.
  * NativeModules.ToastModule in JavaScript.
  * @return name of module refered by JS code
  */
  @Override
  public String getName() {
    return “ToastModule”;
  }

  /**
  * This method returns the constant values exposed to JavaScript.
  * Toast.LENGTH_SHORT will be exposed by ToastModule.SHORT.
  * Toast.LENGTH_LONG will be exposed by ToastModule.LONG.
  * @return maps of JS key to Android constants
  */
  @Override
  public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
    constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
    return constants;
  }

  /**
  * This method is exposed to JS code.
  * It will be used as ToastModule.show(“Hello”, ToastModule.SHORT);
  * All JS exposed method should have @ReactMethod annotation.
  * @param message – String message
  * @param duration – SHORT/LONG duration
  */
  @ReactMethod
  public void show(String message, int duration) {
    Toast.makeText(getReactApplicationContext(), message, duration).show();
  }
}

ToastModule should extends ReactContextBaseJavaModule class from react bridge framework.

getName() returns this module name, referred by JS code, we will set it as ToastModule. So any native calls from JS code will be like ToastModule.show(…) etc, just like Keyboard.

Since, Toast.show has two variants for duration, LENGTH_LONG, LENGTH_SHORT. We need to map to some constants.
getConstants() will do that, it will map SHORT and LONG to respective native constants and will be referred by ToastModule.SHORT or ToastModule.LONG.

Now, we have to expose react native methods, called by JS code.

@ReactMethod
  public void show(String message, int duration) {
    Toast.makeText(getReactApplicationContext(), message, duration).show();
  }
  • All methods, exposed to JS code should have @ReactMethod annotation

This method will be called from JS as, ToastModule.Show(“Hello”,  ToastModule.Short);

Following are the data types accepted by @ReactMethod annotation

Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array

  1. Create package for toast
    1. In ‘toast’ package create another java file – ToastModulePackage.java
package com.nativemodulepackageexample;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ToastModulePackage implements ReactPackage {

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    final List<NativeModule> modules = new ArrayList<>();
    modules.add(new ToastModule(reactContext));
    return modules;
  }
}
  1. ToastModulePackage class should implement ReactPackage interface from react bridge framework.
  2. It will return two native modules, ViewManagers and NativeModules.
  3. Since we are not dealing with ViewManagers that will return empty list.
  4. createNativeModules() will return our implemented module – ToastModule() in a list.
  1. Load/Link package to the app
    1. Now we are done with Module and Package, lets bind this to our application.
    2. Go to “android/app/src/main/java/com/nativemodulepackageexample/MainApplication.java” file
    3. Update ReactNativeHost callback, in getPackages() method
@Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings(“UnnecessaryLocalVariable”)
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          packages.add(new ToastModulePackage());
          return packages;
        }
  • Dont forget to import ToastModulePackage class

Whole file will look a like,

package com.nativemodulepackageexample;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import com.nativemodulepackageexample.toast.ToastModulePackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings(“UnnecessaryLocalVariable”)
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          packages.add(new ToastModulePackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return “index”;
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don’t want Flipper enabled
  }

  /**
  * Loads Flipper in React Native templates.
  *
  * @param context
  */
  private static void initializeFlipper(Context context) {
    if (BuildConfig.DEBUG) {
      try {
        /*
        We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName(“com.facebook.flipper.ReactNativeFlipper”);
        aClass.getMethod(“initializeFlipper”, Context.class).invoke(null, context);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

C. Compiling the code

  1. Go to command line and change to project directory, eg. [react-native-code-base]/ReactModulePackageExample or open terminal in VSC
  2. Run command -> react-native run-android

D. Writing JS code to use ToastModule

  1. In folder NativeModulePackageExample where App.js is stored, create a new folder named “native-modules
  2. Create javascript module file – JSToastModule.js with following code
import {NativeModules} from ‘react-native’;
module.exports = NativeModules.ToastModule;
  1. Here, NativeModules.ToastModule is our native java ToastModule (we set this in getName() function) which got exported.
  2. This needs to be exported to module.exports
  3. This JSToastModule.js will make it easier to other js components or js file to use ToastModule without exporting it every time otherwise you have to export it in every file where you want to use it.

E. Client code for JSToastModule

  1. In App.js use following code
import JSToastModule from “./native-modules/JSToastModule”

JSToastModule.show(‘Hello’, JSToastModule.SHORT);

Now, run following commands,

>react-native run-android [it will compile all native code]

>react-native start [it will run the app]

You will see the toast when app will start.

Note

  1. If you are getting error “Error: listen EADDRINUSE: address already in use :::8081” Use following command to kill node.js instance running on Windows

>taskkill /f /im node.exe

  1. If VSC is not able to recognise ‘toast’ folder as package then open Android Studio and open the android folder of Project in it. Create toast as package and copy both files there. Then use the command [react-native run-android] to compile it. It will work.

GitHub source code – https://github.com/yogeshkalwar/ReactNative/tree/master/NativeModulePackageExample 
Google doc link – https://docs.google.com/document/d/18cIqSc2iwr-MAnB76yrdbRWkSU9MGmmIqRtPdUtdeLo/edit?usp=sharing

Now, it’s Done!!!
Enjoy, happy coding!!!

Template for Generic Component/Screen – ReactNative

While working on ReactNative applications, I found that most of or all most of the components or screen components were same in format. So if you are beginner then following are the basic and generic template while writing any components/screen.

It has 4 parts,
1. Imports of other components
2. declaration of component with props
3. declaration of Stylesheet objects
4. export of component

I am trying to create a component called as Screen, following will be the template for it.

//part 1, with basic import used in almost all components 
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';

//part 2,
const Screen = props => {
return ();
};

//part 3,
const styles = StyleSheet.create({});

//part 4,
export default Screen;

Here, with some example for Header component as component/Header.js file

import React from 'react'
import {View, Text, StyleSheet} from 'react-native'

const Header = props => {
return (
<View style={styles.container}>
<Text>{props.title}</Text>
</View>
};
};
const styles = StyleSheet.create({
container: {
width: '100%',
height: 90,
backgroundColor:'red',
justifyContent:'center',
alignItems:'center'
}
});
export default Header;

that’s Done!!!

Enjoy! Happy coding

Single App with multiple root components while learning – React Native Expo

While learning React Native with multiple examples, if you faced an issue that you need to either override the example in root component file e.g. App.js or creating multiple projects for each example. Here, I found another way to have multiple root component files within single project.

Expo has entry point details, just like other framework – AppEntry.js. This file is stored at /node-modules/expo/AppEntry.js.
When you opens this file, it will looks a like,

import 'expo/build/Expo.fx';
import registerRootComponent from 'expo/build/launch/registerRootComponent';
import { activateKeepAwake } from 'expo-keep-awake';
import App from '../../App';
if (DEV) {
activateKeepAwake();
}
registerRootComponent(App);

so lines, import App from ‘../../App’ , imports App.js and App component and
registerRootComponent(App) registers it as root component.

Now if you want to test FlexBox in another file, preserving App.js then create another
file like FlexBoxExample.js in same folder where App.js is stored. Update AppEntry.js
as below.

import 'expo/build/Expo.fx';
import registerRootComponent from 'expo/build/launch/registerRootComponent';
import { activateKeepAwake } from 'expo-keep-awake';
import FlexBoxExample from '../../ FlexBoxExample ';
if (DEV) {
activateKeepAwake();
}
registerRootComponent( FlexBoxExample );

Save and it’s Done!!!

Enjoy and happy coding.

My first experience with React Native

Well, I am native developer, almost worked for more than 10 years in Android native development. But, this react native stuff forced me to have a look into it, not professionally but atleast a try.
I installed native js and all other stuff as described by https://facebook.github.io/react-native/docs/getting-started.
I started first with React native CLI, did all what mentioned in above official page. But seems it was my bad day and I could not able to run a basic app on Android emulator. Something with Metro Bundler had issues.
Then I tried with Expo, something fantastic framework which has all in one kind of stuff for react native development.
But, remember it was my bad day 🙂 lol, this Expo did not work either but best thing with me was my Patience. I went into depth and digging I found that there is some issue with blacklisting json, damn what is that? I thought it was joke on stackoverflow https://stackoverflow.com/questions/58760712/how-to-fix-metro-bundler-process-exited-with-code-1 , but you know, sometimes funny things are the real solution. and it worked.
So, if you are trying to run your react native app on Android emulator and when u select emulator on Metro Bundler, and you see following error

Metro Bundler process exited with code 1
Set EXPO_DEBUG=true in your env to view the stack trace.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ start: expo start
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ start script.
npm ERR! This is probably not a problem with npm.
There is likely additional logging output above.
  1. Open \node_modules\metro-config\src\defaults\blacklist.js file from your app.
  2. Update following code
var sharedBlacklist = [
/node_modules[/\]react[/\]dist[/\]./, /website\/node_modules\/./,
/heapCapture\/bundle.js/,
/.\/tests\/./
];
to the following code,
var sharedBlacklist = [
   /node_modules[\/\]react[\/\]dist[\/\]./,   /website\/node_modules\/./,
   /heapCapture\/bundle.js/,
   /.\/tests\/./
 ];
3. Save and open command terminal 
    =>cd Your Project path && expo start

And it’s Done!!!

And if app still not loading in emulator and there are errors, then please check your nodejs version, if greater than 12.9.1 then downgrade it.

choco uninstall nodejs
choco install nodejs --version=12.9.1

Enjoy and happy coding.

Androidx Kotlin App – MVVM + Dagger2 + RxJava + Retrofit + Butterknife + Mockito + UnitTest + Robolectric + MockWebServer

Steps:
1. Configure gradle with libs dependencies
2. Create model classes
3. Create repository module
4. Create ViewModel for City
5. Create DI (dependency injection) module
6. Create Unit test
7. Create UI
8. Update Application, DI modules

Let’s start:
1. Configure gradle with libs dependencies

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    //Android
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
    //Networking
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.10.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    //RxJava
    implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    //Timber
    implementation 'com.jakewharton.timber:timber:4.5.1'
    //Dagger2
    def daggerVersion = '2.15'
    kapt "com.google.dagger:dagger-compiler:$daggerVersion"
    kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
    implementation "com.google.dagger:dagger:$daggerVersion"
    implementation "com.google.dagger:dagger-android:$daggerVersion"
    implementation "com.google.dagger:dagger-android-support:$daggerVersion"
    kaptTest "com.google.dagger:dagger:$daggerVersion"
    testImplementation "com.google.dagger:dagger:$daggerVersion"
    //Glide
    implementation 'com.github.bumptech.glide:glide:4.7.1'
    kapt 'com.github.bumptech.glide:compiler:4.7.1'
    //Butterknife
    implementation 'com.jakewharton:butterknife:10.0.0'
    kapt 'com.jakewharton:butterknife-compiler:10.0.0'
    // Mock web server
    testImplementation 'com.squareup.okhttp:mockwebserver:2.7.5'
    // core testing
    testImplementation 'android.arch.core:core-testing:1.1.1'
    // Roboelectric
    testImplementation 'org.robolectric:robolectric:4.3.1'
    //Test
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:2.8.9'
    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
}
android {
    ...
    testOptions{
        unitTests{
            includeAndroidResources true
        }
    }
}

2. Create model classes
I am using Open Weather Map http://api.openweathermap.org/data/2.5/weather?q=London,uk ‘s City weather api to demonstrate the api call.
For Response following model classes will be needed.
a. City

data class City(@SerializedName("coord") var coordinate: Coordinate?,
                @SerializedName("weather") var weather: List<Weather>?,
                @SerializedName("main") var main: Main?,
                @SerializedName("visibility") var visibility: Int = 0,
                @SerializedName("wind") var wind : Wind?,
                @SerializedName("clouds") var clouds: Clouds?,
                @SerializedName("dt") var date: Int,
                @SerializedName("id") var id: Int,
                @SerializedName("name") var name: String,
                @SerializedName("cod") var code: Int) {

    fun getFirstWeather() : Weather? {
        var firstValue: Weather? = null
        val size = weather?.size ?: 0
        if (size > 0) {
            firstValue = weather?.get(0)
        }
        return firstValue;
    }

    override fun toString(): String {
        val buffer: StringBuffer = StringBuffer()
        buffer.append("Coordinate:" + coordinate.toString())
        buffer.append(",\nweather:" + getFirstWeather().toString())
        buffer.append(",\nmain:" + main.toString())
        buffer.append(",\nvisibility:" + visibility)
        buffer.append(",\nwind:" + wind.toString())
        buffer.append(",\nclouds:" + clouds.toString())
        buffer.append(",\ndt:"+date)
        buffer.append(",\nid:"+id)
        buffer.append(",\nname:"+name)
        buffer.append(",\ncod:"+code)
        return buffer.toString()
    }
}

b. Coordinate, Clouds, Main, Weather, Wind

data class Coordinate(@SerializedName("lon") var longitude: Float = 0.0f,
                      @SerializedName("lat") var lattitude: Float = 0.0f) {

    override fun toString(): String {
        return "{lon=%f, lat=%f}".format(longitude, lattitude)
    }
}
data class Clouds(@SerializedName("all") var all: Int = 0) {

    override fun toString(): String {
        return "%d".format(all)
    }
}
data class Main(@SerializedName("temp") var temperature : Float = 0.0f,
                @SerializedName("pressure") var pressure: Int = 0,
                @SerializedName("humidity") var humidity: Int = 0,
                @SerializedName("temp_min") var minTemperature: Float = 0.0f,
                @SerializedName("temp_max") var maxTemperature: Float = 0.0f) {

    override fun toString(): String {
        return "{temp=%f, pressure=%d, humidity=%d, minTemp=%f, maxTemp=%f}".format(temperature, pressure, humidity, minTemperature, maxTemperature)
    }
}
data class Weather(@SerializedName("id") var id: Int = 0,
                   @SerializedName("main") var main: String?,
                   @SerializedName("description") var description: String?,
                   @SerializedName("icon") var icon: String?) {

    override fun toString(): String {
        return "{id=%d, main=%s, desc=%s, icon=%s}".format(id, main, description, icon)
    }
}
data class Wind(@SerializedName("speed") var speed : Float = 0.0f,
                @SerializedName("deg") var degree : Int = 0) {

    override fun toString(): String {
        return "{speed=%f, deg=%d}".format(speed, degree)
    }
}

3. Create repository module –
First we will create interface for client code using repository module
Repository.kt

interface Repository {

    fun getCityWeather(city: String): Single<City>
}

I want repository to provide Network as well as Local response functionalities, even going further with SharedPreference as well as Room database for Local repository.
This could be achieved with Strategy pattern as below,

NetworkOnlyRepository class implements Network api which further uses BackEndService interface to decouple the data providers like LiveApiService for network api or MockApiService for mock api service or local json response converter service.
LocalOnlyRepository class implements local data providers with help from LocalService interface to decouple the providers either as SharedPreference or data base as Room.
We can have another implementation for CachedNetworkRepository which will store the response in database and will provide the data from database for future calls (for those resources which are not going to change or in large).

open class NetworkOnlyRepository: Repository {
    val apiService: Repository
    constructor(apiService: Repository) {
        this.apiService = apiService
    }
    override fun getCityWeather(city: String): Single<City> {
        return apiService.getCityWeather(city)
    }
}

interface BackendService {
    companion object {
        const val QUERY_PARAM = "q"
        const val API_KEY = "APPID"
        const val VERSION = "/data/2.5"
    }
    @GET("/data/2.5/weather")
    fun getCityWeather(@Query(QUERY_PARAM) query : String, @Query(API_KEY) apiKey: String?): Single<City>
}

class LiveApiService: Repository {
    companion object {
        const val CACHE_50MB: Long = 50 * 1024 * 1024
        const val TIMEOUT: Long = 60
    }
    val resource: Resource
    var apiService: BackendService
    var apiKey: String?
    constructor(resource: Resource, allowRetry: Boolean) {
        this.resource = resource
        apiService = init(allowRetry)
        apiKey = resource.getString(Resource.API_KEY)
    }
    private fun init(allowRetry: Boolean): BackendService {
        val cache = Cache(resource.getCacheDir(), CACHE_50MB)
        val client = OkHttpClient.Builder()
            .cache(cache)
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
            .retryOnConnectionFailure(allowRetry)
        if (BuildConfig.DEBUG) {
            val logging = HttpLoggingInterceptor()
            logging.setLevel(HttpLoggingInterceptor.Level.BODY)
            client.addInterceptor(logging)
        }
        //TODO: add interceptors here
        val builder = Retrofit.Builder()
            .baseUrl(getBaseUrl())
            .addConverterFactory(GsonConverterFactory.create(getGson()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(client.build())
        return builder.build().create(BackendService::class.java)
    }
    fun getGson(): Gson {
        val gsonBuilder = GsonBuilder()
        return gsonBuilder.create()
    }
    fun getBaseUrl(): String? {
        return resource.getString(Resource.BASE_URL)
    }
    override fun getCityWeather(city: String): Single<City> {
        return apiService.getCityWeather(city, apiKey)
    }
}

There is one helper class ContextResource I wrote for resource usage like Context, as I do not want all my code to be dependent on Android OS classes like Context to get string or init something. It would help in unit testing also.

interface Resource {
    fun getString(id: String): String?
    fun getCacheDir(): File?
    companion object {
        const val BASE_URL = "base_url"
        const val API_KEY = "api_key"
    }
}

class ContextResource: Resource {

    private val resourceIds: Map<String, Int> = hashMapOf(Resource.BASE_URL to R.string.base_url, Resource.API_KEY to R.string.api_key)

    private val contextWrapper: WeakReference<Context>
    constructor(context: Context) {
        contextWrapper = WeakReference(context)
    }
    override fun getCacheDir(): File? {
        return getContext()?.cacheDir
    }
    override fun getString(name: String): String? {
        val id = resourceIds.get(name)
        var value: String? = null
        if (id != null) {
            value = getContext()?.getString(id)
        }
        return value
    }
    private fun getContext(): Context? {
        return contextWrapper.get()
    }
}

4. Create ViewModel for City
Now we have models, repository, so let’s create ViewModel to interact with View and Repository/Model
Here, I declared ViewModelContract to declare all methods for ViewModel, basically this will decouple you ViewModel from View or the client code of ViewModel.
BaseViewModel is abstract class for basic and common functionalities of ViewModel.
For City, CityWeatherViewModel class takes Repository as constructor injected param, and when load() method is called from View, it makes api call through repository which could be anyone from NetworkOnlyRepository(Live/Mock) or LocalOnlyRepository(SharedPreference/Room) or any other class implementing Repository interface.
OnSuccess – it will update the LiveData variable through data.value, any Observer listening on data(LiveData) will be notified.

interface ViewModelContract {
    fun load()
}

open abstract class BaseViewModel : ViewModel(), ViewModelContract {
}

class CityWeatherViewModel @Inject constructor(private val repository: Repository): BaseViewModel() {

    private val data: MutableLiveData<City> = MutableLiveData()
    override fun load() {
        repository.getCityWeather("London,uk")
        //TODO: You can modify load() which can take city name
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSuccess { t: City? -> onSuccess(t) }
            .doOnError { t: Throwable? ->  Timber.d(t)}
            .subscribe()
    }
    private fun onSuccess( city: City?) {
        data.value = city
        if (city != null) {
            Timber.d(city.name)
        }
    }
    fun getCity(): LiveData<City> = data
}

5. Create DI (dependency injection) module
Now, comes most challenging but very simple module, DI i.e. Dependency Injection with Dagger2.
This will make object creation simple, central, module independent and decoupled and easy for extension and last but not the least app optimal.

AppComponent – Component interface, Dagger will create DaggerAppComponent class for linking Dagger with respective modules and providing way to inject the dependencies to the object.
Here, AppComponent has modules listed below, for individual functionalities like for App, Repository, RxJava, ViewModel and Activities.
Builder interface provided for binding instance and returning instance while building it as well as api for inject.

ApplicationModule – provides App’s Context and ResourceContext
RepositoryModule – provides Repository reference, with NetworkOnlyRepository instance. You can have another provides with named value for other type of repository instance.
RxJavaModule – provides respective schedular on main thread and io.
ViewModelModule – provides ViewModel instance, currently CityWeatherViewModel. Please list all ViewModels here only.
ActivityModule – provides Activity instances, currently MainActivity.
ViewModelFactory

@IntoMap
@ViewModelKey(CityWeatherViewModel::class)
abstract fun bindCityWeatherViewModel(viewModel: CityWeatherViewModel): ViewModel

If you see above code, @ViewModelKey and @IntoMap is used in ViewModelModule to provide the ViewModel. ViewModelFactory uses creators with Map, to return ViewModelProvider.Factory which has create() api to return the respective ViewModel object. This class is generic for all cases, not only to this App but for all app.

@Singleton
@Component(modules = [
    AndroidInjectionModule::class,
    ApplicationModule::class,
    RepositoryModule::class,
    RxJavaModule::class,
    ViewModelModule::class,
    ActivityModule::class])

interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: Application): Builder
        fun build(): AppComponent
    }
    fun inject(app: ArrowApplication)
}

@Module(includes = arrayOf(ViewModelModule::class))
internal class ApplicationModule {
    @Singleton
    @Provides
    fun providesContext(app: Application) : Context = app

    @Singleton
    @Provides
    fun providesContextResource(app: Context): Resource = ContextResource(app)
}

@Module
class RepositoryModule {
    @Singleton
    @Provides
    fun provideRepository(resource: Resource):
            Repository = NetworkOnlyRepository(LiveApiService(resource, true))
}

@Module
class RxJavaModule {
    @Provides
    @Named("SubscribeOn")
    fun provideSubscribeOn(): Scheduler = Schedulers.io()

    @Provides
    @Named("ObserverOn")
    fun provideObserveOn(): Scheduler = AndroidSchedulers.mainThread()
}

@Module
internal abstract class ViewModelModule {
    @Binds
    @IntoMap
    @ViewModelKey(CityWeatherViewModel::class)
    abstract fun bindCityWeatherViewModel(viewModel: CityWeatherViewModel): ViewModel
}

@Module
abstract class ActivityModule {
    @ActivityScope
    @ContributesAndroidInjector
    abstract fun bindMainActivity(): MainActivity
}

@Singleton
class ViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        var creator: Provider<out ViewModel>? = creators.get(modelClass)
        if (creator == null) {
            for (entry in creators.entries) {
                if (modelClass.isAssignableFrom(entry.key)) {
                    creator = entry.value
                    break
                }
            }
        }
        if (creator == null) {
            throw IllegalArgumentException("Unknown model class $modelClass") 
                   as Throwable
        }

        try {
            return creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}

Dagger components:

Application package structure:

6. Create Unit test
Since we have MockWebServer and RxJava, we need to have few stubs ready before writing unit test cases.
TrampolineScheduler will be used to make all RxJava calls, its non-blocking FIFO based and called on same thread. To use this we will write TestRule for that RxImmediateSchedularRule class.

class RxImmediateSchedulerRule : TestRule {
    override fun apply(base: Statement, d: Description): Statement {
        return object : Statement() {
            @Throws(Throwable::class)
            override fun evaluate() {
                RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
                RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() }
                RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() }
                RxAndroidPlugins.setInitMainThreadSchedulerHandler { 
                                      Schedulers.trampoline() }

                try {
                    base.evaluate()
                } finally {
                    RxJavaPlugins.reset()
                    RxAndroidPlugins.reset()
                }
            }
        }
    }
}

Now we need base class for unit test cases which makes api calls – BaseTest
isMockServerEnabled() will give you edge to have BaseTest available to all non api call maker unit test classes, so there you don’t have to initialise MockWebServer.

abstract class BaseTest {

    lateinit var mockServer: MockWebServer
    lateinit var testAppComponent: TestAppComponent
    @Inject lateinit var viewModelFactory: ViewModelFactory

    @Before
    open fun setup() {
        initMockServer()
        initDagger()
    }

    @After
    open fun tearDown() {
        stopMockServer()
    }

    open fun initMockServer() {
        if (isMockServerEnabled()) {
            mockServer = MockWebServer()
            mockServer.start()
        }
    }

    open fun initDagger() {
        testAppComponent = DaggerTestAppComponent.builder().repositoryModule(
            RepositoryModule()).testRxJavaModule(TestRxJavaModule()).build()
        testAppComponent.inject(this)
    }

    open fun stopMockServer() {
        if (isMockServerEnabled()) {
            mockServer.shutdown()
        }
    }

    open fun mockHttpResponse(filename: String, responseCode: Int) = 
                               mockServer.enqueue(MockResponse()
        .setResponseCode(responseCode)
        .setBody(getJson(filename)))

    private fun getJson(filePath: String): String {
        val uri = this.javaClass.classLoader.getResource(filePath)
        val file = File(uri.path)
        return String(file.readBytes())
    }

    abstract fun isMockServerEnabled(): Boolean
}

Dagger in unit test cases- Simply override all Schedulars to main thread, provide app resources, and injection for BaseTest(in app you will be injecting activity).

@Module
class TestRxJavaModule {
    @Provides
    @Named("SubscribeOn")
    @Singleton
    fun provideSuscriberOn(): Scheduler = AndroidSchedulers.mainThread()
    @Provides
    @Named("ObserverOn")
    @Singleton
    fun provideObserverOn(): Scheduler = AndroidSchedulers.mainThread()
}

@Module(includes = arrayOf(ViewModelModule::class))
internal class TestApplicationModule {
    @Singleton
    @Provides
    fun providesContext(app: Application) : Context = app
    @Singleton
    @Provides
    fun providesContextResource(): Resource = TestResource()
}

@Singleton
@Component(modules = [
    TestApplicationModule::class,
    RepositoryModule::class,
    TestRxJavaModule::class])
interface TestAppComponent {
    fun inject(baseTest: BaseTest)
}

Class for Resource – TestResource
Here we are overriding base url with “/” as MockWebServer makes it to local.

class TestResource: Resource {

    private val resourceIds: Map<String, String> = hashMapOf(Resource.BASE_URL to "/", 
                                    Resource.API_KEY to "")

    override fun getCacheDir(): File? = null

    override fun getString(name: String): String? = resourceIds.get(name)
}

First Unit test class – NetworkOnlyRepositoryTest without MockWebServer
Here I have created response object on the fly.

class NetworkOnlyRepositoryTest {

    @Rule @JvmField val rule = MockitoJUnit.rule()!!
    @Rule @JvmField var testSchedularRule = RxImmediateSchedulerRule()
    @Mock lateinit var repository: Repository
    internal lateinit var networkOnlyRepository: NetworkOnlyRepository

    @Before
    fun setup() {
        networkOnlyRepository = NetworkOnlyRepository(repository)
    }

    @Test
    fun testCityWeatherApi() {
        val response = City(Coordinate(-0.13f, 51.51f),
            listOf(Weather(800, "Clear", "clear sky", "01d")),
            Main(283.41f, 1025, 76, 281.48f, 285.37f),
            10000, Wind(1.5f), Clouds(0), 1571738787, 2643743, "London", 200)
        Mockito.`when`(repository.getCityWeather("London")).thenReturn(Single.just(response))
        val result = networkOnlyRepository.getCityWeather("London")
        val testObserver = TestObserver<City>()
        result.subscribe(testObserver)
        testObserver.assertComplete()
        testObserver.assertNoErrors()
        testObserver.assertValueCount(1)
        val city = testObserver.values()[0]
        assertThat(city.coordinate?.longitude, `is`(-0.13f))
        assertThat(city.coordinate?.lattitude, `is`(51.51f))
        assertThat(city.weather?.get(0)?.id, `is`(800))
        assertThat(city.weather?.get(0)?.main, `is`("Clear"))
        assertThat(city.weather?.get(0)?.description, `is`("clear sky"))
        assertThat(city.id, `is`(2643743))
        assertThat(city.name, `is`("London"))
        assertThat(city.code, `is`(200))
    }
}

My second Unit test class – CityTest using MockWebServer to test CityWeatherViewModel
a. Using test rule RxImmediateSchedulerRule to use Trampoline for all RxJava schedular calls
b. Using Robolectric to have Activity
c. Using CityWeatherViewModel to test

mockHttpResponse(“city.json”, HttpURLConnection.HTTP_OK)
//This will make MockWebServer to mimic http ok state
assertEquals(“City should be null as stream not started yet”, viewModel.getCity().value, null)
//This will assert if not equal, that city value should be null before call made.
viewModel.load()
//Make actual load() api call on CityWeatherViewModel instance
assertEquals(“London”, viewModel.getCity().value?.name)
//This will assert if not equal, city name should be “London”

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1])
class CityTest: BaseTest() {
    @Rule
    @JvmField
    val immediateSchedulerRule = RxImmediateSchedulerRule()

    private lateinit var activity: MainActivity
    private lateinit var viewModel: CityWeatherViewModel

    override fun isMockServerEnabled(): Boolean = true

    @Before
    override fun setup() {
        super.setup()
        activity = Robolectric.setupActivity(MainActivity::class.java)
        viewModel = ViewModelProviders.of(activity, viewModelFactory)[CityWeatherViewModel::class.java]
    }

    @Test
    fun getCityWhenSuccess() {
        mockHttpResponse("city.json", HttpURLConnection.HTTP_OK)
        assertEquals("City should be null as stream not started yet", viewModel.getCity().value, null)
        viewModel.load()
        assertEquals("London", viewModel.getCity().value?.name)
    }
}

Application package structure for unit tests –

7. Create UI
UI part is very straight forward with base classes and MainActivity composing with ViewModel

abstract class BaseActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        initDagger()
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
    }
    open fun initDagger() {
        AndroidInjection.inject(this)
    }
    abstract open fun getLayoutId(): Int
}

interface ViewContract<T> {
    fun onDataUpdate(data: T)
}

class MainActivity : BaseActivity() {
    @BindView(R.id.activity_main_weather)
    lateinit var weatherText: TextView
    @Inject lateinit var viewModelFactory: ViewModelFactory
    lateinit var viewModelContract: ViewModelContract

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        ButterKnife.bind(this)
        init()
    }
    private fun init() {
        viewModelContract = ViewModelProviders.of(this, 
                          viewModelFactory).get(CityWeatherViewModel::class.java)
        (viewModelContract as CityWeatherViewModel).getCity().observe(this, Observer { 
                                         city -> onDataUpdate(city)})
        viewModelContract.load()//TODO: move this code to on button click, as unit test 
        //case makes manual load() call. 
    }
    fun onDataUpdate(city: City) {
        weatherText.setText(city.toString())
    }
    override fun getLayoutId(): Int = R.layout.activity_main
}

8. Update Application, DI modules
So, finally everything done except last but not least, Application class which initialises the Dagger.
DispatchingAndroidInjector classes is something does dirty work for you where you don’t have to write stubs for injecting core components like Activity, Service, Fragment.

open class ArrowApplication: Application(), HasActivityInjector {
    @Inject
    lateinit var activityInjector : DispatchingAndroidInjector<Activity>
    override fun onCreate() {
        super.onCreate()
        initDagger()
    }
    private fun initDagger() {
        DaggerAppComponent.builder().application(this).build().inject(this)
    }
    override fun activityInjector(): AndroidInjector<Activity> = activityInjector
}

So enjoy MVVM with Dagger, RxJava, MockWebServer…

Overall flow of application:

Source code Weather app – https://github.com/yogeshkalwar/Arrow