MVVM Kotlin Android Architecture

Overview

Model-View-ViewModel (ie MVVM)

Android Arsenal kotlin coroutines Mockk Junit5 Espresso Dagger 2 Kotlin-Android-Extensions MVVM MVP Build StatusMVVM3

Model-View-ViewModel (ie MVVM) is a template of a client application architecture, proposed by John Gossman as an alternative to MVC and MVP patterns when using Data Binding technology. Its concept is to separate data presentation logic from business logic by moving it into particular class for a clear distinction. You can also check MVP

Why Promoting MVVM VS MVP:

  • ViewModel has Built in LifeCycleOwerness, on the other hand Presenter not, and you have to take this responsiblty in your side.
  • ViewModel doesn't have a reference for View, on the other hand Presenter still hold a reference for view, even if you made it as weakreference.
  • ViewModel survive configuration changes, while it is your own responsiblities to survive the configuration changes in case of Presenter. (Saving and restoring the UI state)

MVVM Best Pratice:

  • Avoid references to Views in ViewModels.
  • Instead of pushing data to the UI, let the UI observe changes to it.
  • Distribute responsibilities, add a domain layer if needed.
  • Add a data repository as the single-point entry to your data.
  • Expose information about the state of your data using a wrapper or another LiveData.
  • Consider edge cases, leaks and how long-running operations can affect the instances in your architecture.
  • Don’t put logic in the ViewModel that is critical to saving clean state or related to data. Any call you make from a ViewModel can be the last one.

What is Coroutines ?

Coroutines : Is light wight threads for asynchronous programming, Coroutines not only open the doors to asynchronous programming, but also provide a wealth of other possibilities such as concurrency, actors, etc.


Coroutines VS RXJava

They're different tools with different strengths. Like a tank and a cannon, they have a lot of overlap but are more or less desirable under different circumstances. - Coroutines Is light wight threads for asynchronous programming. - RX-Kotlin/RX-Java is functional reactive programming, its core pattern relay on observer design pattern, so you can use it to handle user interaction with UI while you still using coroutines as main core for background work.

How does Coroutines concept work ?

  • Kotlin coroutine is a way of doing things asynchronously in a sequential manner. Creating a coroutine is a lot cheaper vs creating a thread.

When I can choose Coroutines or RX-Kotlin to do some behaviour ?

  • Coroutines : When we have concurrent tasks , like you would fetch data from Remote connections , database , any background processes , sure you can use RX in such cases too, but it looks like you use a tank to kill ant.
  • RX-Kotlin : When you would to handle stream of UI actions like : user scrolling , clicks , update UI upon some events .....ect .

What is the Coroutines benefits?

  • Writing an asynchronous code is sequential manner.
  • Costing of create coroutines are much cheaper to crate threads.
  • Don't be over engineered to use observable pattern, when no need to use it.
  • parent coroutine can automatically manage the life cycle of its child coroutines for you.

Handle Retrofit with Coroutines

8399

  • Add Coroutines to your gradle file
// Add Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.2'
// Add Retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
  • Make Retrofit Calls.
    @GET("topstories/v2/home.json")
    suspend fun fetchNews(): Response<NewsModel>
  • With async we create new coroutine and returns its future result as an implementation of [Deferred].
  • The coroutine builder called launch allow us to start a coroutine in background and keep working in the meantime.
  • so async will run in background then return its promised result to parent coroutine which created by launch.
  • when we get a result, it is up to us to do handle the result.
    newsMutableLiveData.postValue(Resource.Loading())
        launch {
            try {
                serviceResponse = dataRepository.requestNews()
                newsMutableLiveData.postValue(serviceResponse)
            } catch (e: Exception) {
                newsMutableLiveData.postValue(Resource.DataError(NETWORK_ERROR))
            }
        }

Keep your code clean according to MVVM

  • Yes , liveData is easy , powerful , but you should know how to use.
  • For livedate which will emit data stream , it has to be in your data layer , and don't inform those observables any thing else like in which thread those will consume , cause it is another
  • For livedata which will emit UI binding events, it has to be in your ViewModel Layer.
  • Observers in UI Consume and react to live data values and bind it. responsibility , and according to Single responsibility principle in SOLID (object-oriented design) , so don't break this concept by mixing the responsibilities .

mvvm2

LICENSE

Copyright [2016] [Ahmed Eltaher] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

You might also like...
GraphQLTrial is a demo application based on modern Android application tech-stacks and MVVM architecture.

GraphQLTrial is a demo application based on modern Android application tech-stacks and MVVM architecture. App fetching data from the netw

A simple Android Application with MVVM Architecture, Coroutine, Retrofit2

Retrofit with Coroutines and MVVM Architecture. A simple Android Application with MVVM Architecture Developed Using LiveData. MVVM Architecture. Retro

Keep  My Notes App Android MVVM architecture
Keep My Notes App Android MVVM architecture

Keep My Notes My Notes. lien PlayStore Screenshots Architecture This app implements the MVVM architectural . Built with ViewModel - A class designed t

Currency converter Android application using MVVM architecture
Currency converter Android application using MVVM architecture

Currency Converter Currency conversion using live exchange rates. Demo Screenshots API service

❤️ Android Ghibli using Hilt, Motion, Coroutines, Jetpack (ViewModel) based on MVVM architecture.

Glibhi ❤️ Android Ghibli using Hilt, Motion, Coroutines, Jetpack (ViewModel) based on MVVM architecture. Tech stack & Open-source libraries Minimum SD

Android MVVM Base Architecture for Enterprise Mobile Application using Architectural Components
Android MVVM Base Architecture for Enterprise Mobile Application using Architectural Components

Android MVVM Base Architecture for Enterprise Mobile Application using Architectural Components Highlights MVVM Architectural pattern Offline Support

A small demo application based on modern Android application technology stacks and MVVM architecture
A small demo application based on modern Android application technology stacks and MVVM architecture

Pokedex Pokedex es una pequeña aplicación de demostración basada en modernas pil

A more lightweight and simpler to use MVVM architecture for Android.
A more lightweight and simpler to use MVVM architecture for Android.

A more lightweight and simpler to use MVVM architecture for Android, Data and views are two-way bound.

Basic-MVVM-Example - Basic Android Application MVVM
Basic-MVVM-Example - Basic Android Application MVVM

Android's MVVM Architecture in Kotlin Why a simple app ? Because it's easier to

Owner
Tuan
Tuan
📊 A Minimal Expense Tracker App built to demonstrate the use of modern android architecture component with MVVM Architecture

Expenso ?? A Simple Expense Tracker App ?? built to demonstrate the use of modern android architecture component with MVVM Architecture ?? . Made with

Sanju S 813 Dec 30, 2022
Chat App MVVM + Clean ArchitectureChat App MVVM + Clean Architecture

Chat App MVVM + Clean Architecture This Android application built using MVVM + Clean Architecture architecture approach and is written 100% in Kotlin.

null 4 Nov 29, 2022
An android app built using Kotlin following Multi-Module Clean Architecture MVVM

RickyandMorty An android app built using Kotlin that consumes RickyadMorty API to display characters.It has been built following Clean Architecture Pr

Kibet 14 Sep 2, 2022
JeTaxi is built on Clean Architecture-MVVM with Kotlin and follows modern android development trends.

JeTaxi is built on Clean Architecture-MVVM with Kotlin and follows modern android development trends. Also, It uses some of Jetpack and popular libraries. These are Kotlin Coroutine-Flow, kotlinx.serialization, Hilt, Compose, Accompanist, Retrofit2, OkHttp3, Chucker, MockWebServer, Truth.

Tolga Bolatcan 13 Nov 2, 2022
MVVM Kotlin Android Architecture

Model-View-ViewModel (ie MVVM) Model-View-ViewModel (ie MVVM) is a template of a client application architecture, proposed by John Gossman as an alter

Tuan 2 Mar 13, 2022
MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, Kotlin, navigation component, and so on...

MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, kotlin, navigation component, and so on...

Isaias Cuvula 23 Dec 5, 2022
Clean Architecture - Kotlin, MVVM, Use cases

CleanArchitecture Is Clean Architecture only MVVM ? NO, MVVM is a part of clean architecture. MVVM includes Model, View and ViewModel and in addition

Deepanshi bajaj 25 Nov 29, 2022
Ceci est une application d'actualités de l'architecture MVVM avec Kotlin

MVVM-Appli Infos Ceci est une application d'actualités de l'architecture MVVM avec Kotlin utilisant des composants : Retrofit, Room, Coroutines, et Na

Yannick Loic 0 Nov 4, 2021
🧬 Android DataBinding kit for notifying data changes from Model layers to UI layers on MVVM architecture.

?? Android DataBinding kit for notifying data changes from Model layers to UI layers on MVVM architecture.

Jaewoong Eum 275 Dec 21, 2022
An Android Template with MVVM and Clean Architecture

MVVMTemplate ??‍ A simple Android template that lets you create an Android project quickly. How to use ?? Just click on button to create a new repo st

Hossein Abbasi 561 Jan 8, 2023