Coroutines with Retrofit



Project Structure

Project 
  • build.gradle
  • MyAPI.kt
  • MyInterceptor.kt
  • Comment.kt
  • Manifest.xml
  • MainActivity.kt
  • MainActivityWithCt.kt

 retrofit without coroutines

build.gradle

dependencies {

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
}

MyAPI.kt
import com.rayhub.coroutinesretrofit.data.Comment
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET

interface MyAPI {

//Coroutines
@GET("/comments")
fun getComments(): Response<List<Comment>>

//Default
@GET("/comments")
fun getCommentsCall(): Call<List<Comment>>
}

MyInterceptor.kt
import okhttp3.Interceptor
import okhttp3.Response

class MyInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
.newBuilder()
.addHeader("Context-Type", "application/json")
.build()
return chain.proceed(request)
}
}

Manifest.xml


<uses-permission android:name="android.permission.INTERNET" />


Comment.kt
data class Comment(
val body: String,
val email: String,
val id: Int,
val name: String,
val postId: Int
)

MainActivity.kt

package com.rayhub.coroutinesretrofit

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.rayhub.coroutinesretrofit.api.MyAPI
import com.rayhub.coroutinesretrofit.api.MyInterceptor
import com.rayhub.coroutinesretrofit.data.Comment
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.logging.HttpLoggingInterceptor


const val BASE_URL = "https://jsonplaceholder.typicode.com"

class MainActivity : AppCompatActivity() {

val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val logging : HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
var client = OkHttpClient.Builder().apply {
addInterceptor(MyInterceptor())
addInterceptor(logging)
}.build()

val api = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(MyAPI::class.java)

api.getComments().enqueue(object : Callback<List<Comment>>{
override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
Log.e(TAG, "ERROR: $t")
}

override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
if(response.isSuccessful){
response.body()?.let {
for (comment in it){
Log.d(TAG, comment.toString())
}
}
}
}
})

}
}

retrofit with coroutines

MainActivityWithCt.kt


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.rayhub.coroutinesretrofit.api.MyAPI
import com.rayhub.coroutinesretrofit.api.MyInterceptor
import com.rayhub.coroutinesretrofit.data.Comment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.*
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.math.log

class MainActivityWithCt : AppCompatActivity() {

val BASE_URL = "https://jsonplaceholder.typicode.com"
val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_with_ct)

val logging : HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(
HttpLoggingInterceptor.Level.BODY)
var client = OkHttpClient.Builder().apply {
addInterceptor(MyInterceptor())
addInterceptor(logging)
}.build()

val api = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(MyAPI::class.java)

// GlobalScope.launch(Dispatchers.IO) {
// val comments = api.getComments().await()
// for (comment in comments){
// Log.d(TAG, comment.toString())
// }
// }

GlobalScope.launch(Dispatchers.IO) {
val response = api.getComments()
if(response.isSuccessful){
for (comment in response.body()!!){
Log.d(TAG, comment.toString())
}
}
}

}
}

Install/Setup Nodejs 14.17.3(LTS) on cpanel



1. Log in to your account using SS

2. Download the NodeJS

wget https://nodejs.org/dist/latest/node-v14.17.3-linux-arm64.tar.xz

 

3. Extract

tar xvf node-v14.17.3-linux-arm64.tar.xz

 

4. Now rename the folder to nodejs name, to do this type the following command

mv node-v14.17.3-linux nodejs

 

5. Now install node and npm binaries, type the next commands:

mkdir ~/bin
cp nodejs/bin/node ~/bin
cd ~/bin
ln -s ../nodejs/lib/node_modules/npm/bin/npm-cli.js npm

 

6. Node.js and npm are installed on your account. To verify, type the following commands

node --version
npm --version

 

7. Start Node.js Application

npm start

 

9. Integrating a Node.js application with the web server(optional)

In a text editor, add the following lines to the .htaccess file in the/home/username/public_html directory

RewriteEngine On
RewriteRule ^$ http://127.0.0.1:portno/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:portno/$1 [P,L]

 

Using Flash in Nodejs ejs


 Flash ကို အသုံးပြုဖို့ အရင်ဆုံး flash ကို install လုပ်ဖို့ လိုပါမယ်..


npm i express-flash --save


app.js မှာ express flash ကို import လုပ်ပါ


const flash = require('express-flash');


var app = express();


app.use(flash());


ejs မှာ

<% if (messages.error) { %>
          <div class="alert alert-danger"><%- messages.error %></div>
        <% } %>
        <% if (messages.success) { %>
          <div class="alert alert-success"><%- messages.success %></div>
 <% } %>


controller မှာ

req.flash('error'"Password not match!");



Installing Yeoman | Brower and Grunt Cli in ubuntu


 Nodejs Scaffold Generator တစ်ခုဖြစ်တဲ့ yeoman , package Manager ဖြစ်တဲ့ bower နဲ့ Build tool တစ်ခုဖြစ်တဲ့ grunt-cli ကို global အနေနဲ့ install ပြုလုပ်ခြင်း

sudo apt-get install nodejs nodejs-legacy

sudo npm install -g yo bower grunt-cli

 

နမူနာ boilerplate generator များ အဆင်သင့် install ပြုလုပ်ထားခြင်း


sudo npm install -g generator-webapp

sudo npm install -g generator-backbone

 

Thanks.