Skip to content

Commit fb26b71

Browse files
author
Vimalraj Vijay
committed
Interceptor Added and Coroutines Update
1 parent 31483b7 commit fb26b71

File tree

16 files changed

+212
-64
lines changed

16 files changed

+212
-64
lines changed

app/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ dependencies {
5252
implementation 'android.arch.lifecycle:extensions:1.1.1'
5353
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
5454
implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0"
55+
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
5556

5657
//Retrofit
5758
implementation 'com.squareup.retrofit2:retrofit:2.7.2'

app/src/main/AndroidManifest.xml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
33
package="com.vimalvijay.mymodule">
44

5-
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
5+
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
6+
<uses-permission android:name="android.permission.INTERNET"/>
67

78
<application
89
android:name="com.vimalvijay.mymodule.di.ApplicationController"
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.vimalvijay.mymodule.commonutils
2+
3+
import androidx.appcompat.app.AppCompatActivity
4+
import com.vimalvijay.mymodule.network.responsehandler.Resource
5+
6+
open class BaseActivity : AppCompatActivity() {
7+
8+
open fun <T> getResponse(isFromHeros: String, it: Resource<T>?) {}
9+
}

app/src/main/java/com/vimalvijay/mymodule/network/BaseRepository.kt renamed to app/src/main/java/com/vimalvijay/mymodule/commonutils/BaseRepository.kt

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
1-
package com.vimalvijay.mymodule.network
1+
package com.vimalvijay.mymodule.commonutils
22

33
import android.util.Log
4+
import com.vimalvijay.mymodule.network.responsehandler.NetworkResultHandler
45
import retrofit2.Response
5-
import java.io.IOException
66

77
open class BaseRepository {
88

99
/**
1010
* Api Calling
1111
*/
1212
suspend fun <T : Any> safeApiRequest(
13-
call: suspend () -> Response<T>,
14-
errorMessage: String
13+
call: suspend () -> Response<T>
1514
): T? {
16-
val result: NetworkResultHandler<T> = safeApiResult(call, errorMessage)
15+
val result: NetworkResultHandler<T> = safeApiResult(call)
1716
var data: T? = null
1817

1918
when (result) {
2019
is NetworkResultHandler.OnSuccessResponse ->
2120
data = result.response
22-
is NetworkResultHandler.OnFailureResponse ->
23-
Log.d("1.DataRepository", "$errorMessage & Exception - ${result.exception}")
21+
is NetworkResultHandler.OnFailureResponse -> {
22+
Log.d("BaseRepository", "Exception - ${result.exception}")
23+
throw Exception(result.exception.message)
24+
}
2425
}
2526

2627
return data
@@ -30,12 +31,16 @@ open class BaseRepository {
3031
* NetWork Result Handler
3132
*/
3233
private suspend fun <T : Any> safeApiResult(
33-
call: suspend () -> Response<T>,
34-
errorMessage: String
34+
call: suspend () -> Response<T>
3535
): NetworkResultHandler<T> {
3636
val response = call.invoke()
37-
if (response.isSuccessful) return NetworkResultHandler.OnSuccessResponse(response.body()!!)
37+
if (response.isSuccessful) return NetworkResultHandler.OnSuccessResponse(
38+
response.body()!!
39+
)
40+
41+
return NetworkResultHandler.OnFailureResponse(
42+
Exception(response.message())
43+
)
3844

39-
return NetworkResultHandler.OnFailureResponse(IOException("Error Occurred during getting safe Api result, Custom ERROR - $errorMessage"))
4045
}
4146
}

app/src/main/java/com/vimalvijay/mymodule/di/ApplicationController.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,4 @@ import android.app.Application
44
import dagger.hilt.android.HiltAndroidApp
55

66
@HiltAndroidApp
7-
class ApplicationController : Application() {
8-
9-
}
7+
class ApplicationController : Application()

app/src/main/java/com/vimalvijay/mymodule/di/modules/AppModule.kt

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
package com.vimalvijay.mymodule.di.modules
22

3+
import android.content.Context
34
import com.google.gson.FieldNamingPolicy
45
import com.google.gson.GsonBuilder
56
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
67
import com.vimalvijay.mymodule.BuildConfig
78
import com.vimalvijay.mymodule.commonutils.CustomProgressbar
8-
import com.vimalvijay.mymodule.network.ApiConstants
9-
import com.vimalvijay.mymodule.network.ApiService
9+
import com.vimalvijay.mymodule.network.api.ApiConstants
10+
import com.vimalvijay.mymodule.network.api.ApiService
11+
import com.vimalvijay.mymodule.network.interceptors.LoggingInterceptor
1012
import dagger.Module
1113
import dagger.Provides
1214
import dagger.hilt.InstallIn
1315
import dagger.hilt.android.components.ApplicationComponent
16+
import dagger.hilt.android.qualifiers.ApplicationContext
1417
import okhttp3.OkHttpClient
1518
import okhttp3.logging.HttpLoggingInterceptor
1619
import retrofit2.Retrofit
@@ -32,15 +35,17 @@ class AppModule {
3235
*/
3336
@Provides
3437
@Singleton
35-
fun provideOkHttpClient(): OkHttpClient = if (BuildConfig.DEBUG) {
38+
fun provideOkHttpClient(@ApplicationContext context: Context): OkHttpClient {
3639
val loggingInterceptor = HttpLoggingInterceptor()
3740
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
38-
OkHttpClient.Builder()
39-
.addInterceptor(loggingInterceptor)
40-
.build()
41-
} else OkHttpClient
42-
.Builder()
43-
.build()
41+
val okHttpClient = OkHttpClient.Builder()
42+
if (BuildConfig.DEBUG) {
43+
okHttpClient.addInterceptor(loggingInterceptor)
44+
}
45+
// okHttpClient.addInterceptor(ErrorInterceptor(context))
46+
okHttpClient.addInterceptor(LoggingInterceptor(context))
47+
return okHttpClient.build()
48+
}
4449

4550

4651
/**
@@ -67,7 +72,9 @@ class AppModule {
6772
*/
6873
@Provides
6974
@Singleton
70-
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
75+
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(
76+
ApiService::class.java
77+
)
7178

7279

7380
/**
Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package com.vimalvijay.mymodule.main.repository
22

3+
import com.vimalvijay.mymodule.commonutils.BaseRepository
34
import com.vimalvijay.mymodule.main.model.Hero
4-
import com.vimalvijay.mymodule.network.ApiService
5-
import com.vimalvijay.mymodule.network.BaseRepository
5+
import com.vimalvijay.mymodule.network.api.ApiService
66
import javax.inject.Inject
77

88

@@ -14,9 +14,7 @@ class MainRepository @Inject constructor(var apiService: ApiService) : BaseRepos
1414
suspend fun getHerosList(): MutableList<Hero.HeroItem>? {
1515

1616
val heroResponse = safeApiRequest(
17-
call = { apiService.getHeroes().await() },
18-
errorMessage = "Error On" + Thread.currentThread().stackTrace[1].methodName
19-
)
17+
call = { apiService.getHeroes().await() })
2018
return heroResponse?.toMutableList()
2119
}
2220
}
Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,87 @@
11
package com.vimalvijay.mymodule.main.ui
22

3-
import android.app.ProgressDialog
43
import android.os.Bundle
54
import android.view.LayoutInflater
65
import android.view.View
76
import android.widget.LinearLayout
87
import android.widget.TextView
8+
import android.widget.Toast
99
import androidx.activity.viewModels
10-
import androidx.appcompat.app.AppCompatActivity
1110
import androidx.lifecycle.Observer
1211
import com.vimalvijay.mymodule.R
12+
import com.vimalvijay.mymodule.commonutils.BaseActivity
1313
import com.vimalvijay.mymodule.commonutils.CustomProgressbar
1414
import com.vimalvijay.mymodule.main.model.Hero
1515
import com.vimalvijay.mymodule.main.viewmodel.MainViewModel
16+
import com.vimalvijay.mymodule.network.responsehandler.Resource
17+
import com.vimalvijay.mymodule.network.responsehandler.Status
1618
import dagger.hilt.android.AndroidEntryPoint
1719
import javax.inject.Inject
1820

1921

2022
@AndroidEntryPoint
21-
class MainActivity : AppCompatActivity() {
23+
class MainActivity : BaseActivity() {
2224

2325
@Inject
2426
lateinit var customProgressbar: CustomProgressbar
2527

2628
lateinit var view: View
2729

2830
private val mainViewModel: MainViewModel by viewModels()
29-
var progress: ProgressDialog? = null
31+
3032

3133
override fun onCreate(savedInstanceState: Bundle?) {
3234
super.onCreate(savedInstanceState)
3335
setContentView(R.layout.activity_main)
34-
progress = ProgressDialog(this)
35-
/**
36-
* Fetch
37-
*/
38-
39-
/*progress!!.setTitle("Loading")
40-
progress!!.setMessage("Wait while loading...")
41-
progress!!.setCancelable(false) // disable dismiss by tapping outside of the dialog
42-
43-
progress!!.show()*/
44-
customProgressbar.showProgress(this)
45-
mainViewModel.fetchHerosList()
4636
/**
4737
* Observe Using Live data
4838
*/
49-
mainViewModel.heroListLiveData.observe(
50-
this,
51-
Observer<MutableList<Hero.HeroItem>> { t -> generateView(t) })
39+
mainViewModel.heroListLiveData().observe(this, Observer {
40+
getResponse("Heros", it)
41+
})
5242
}
5343

5444
/**
5545
* Set Views
5646
*/
5747
private fun generateView(hero: MutableList<Hero.HeroItem>?) {
5848
customProgressbar.hideProgress()
59-
val parentLayout = findViewById<LinearLayout>(R.id.llt_heros_list)
60-
val layoutInflater: LayoutInflater = layoutInflater
49+
if (hero != null) {
50+
val parentLayout = findViewById<LinearLayout>(R.id.llt_heros_list)
51+
val layoutInflater: LayoutInflater = layoutInflater
52+
53+
parentLayout.removeAllViews()
54+
for (i in hero.indices) {
55+
view = layoutInflater.inflate(R.layout.heros_name_list, parentLayout, false)
56+
val tvHeroNames = view.findViewById<TextView>(R.id.tv_hero_names)
57+
tvHeroNames.text = hero[i].name
58+
parentLayout.addView(view)
59+
}
60+
} else {
61+
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show()
62+
}
63+
}
64+
65+
override fun <T> getResponse(isFromHeros: String, it: Resource<T>?) {
66+
it?.let { resource ->
67+
when (resource.status) {
68+
Status.LOADING -> {
69+
customProgressbar.showProgress(this)
70+
}
71+
Status.SUCCESS -> {
72+
if (isFromHeros.equals("Heros")) {
73+
generateView(it.data as MutableList<Hero.HeroItem>)
74+
} else {
75+
// get Another Response
76+
}
77+
}
78+
Status.ERROR -> {
79+
println("resources = ${resource.message}")
80+
Toast.makeText(this, resource.message, Toast.LENGTH_SHORT).show()
81+
customProgressbar.hideProgress()
82+
}
6183

62-
parentLayout.removeAllViews()
63-
for (i in hero?.indices!!) {
64-
view = layoutInflater.inflate(R.layout.heros_name_list, parentLayout, false)
65-
val tvHeroNames = view.findViewById<TextView>(R.id.tv_hero_names)
66-
tvHeroNames.text = hero[i].name
67-
parentLayout.addView(view)
84+
}
6885
}
6986
}
7087
}

app/src/main/java/com/vimalvijay/mymodule/main/viewmodel/MainViewModel.kt

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,14 @@ package com.vimalvijay.mymodule.main.viewmodel
33
import androidx.hilt.lifecycle.ViewModelInject
44
import androidx.lifecycle.MutableLiveData
55
import androidx.lifecycle.ViewModel
6+
import androidx.lifecycle.liveData
67
import com.vimalvijay.mymodule.main.model.Hero
78
import com.vimalvijay.mymodule.main.repository.MainRepository
8-
import kotlinx.coroutines.*
9+
import com.vimalvijay.mymodule.network.responsehandler.Resource
10+
import kotlinx.coroutines.CoroutineScope
11+
import kotlinx.coroutines.Dispatchers
12+
import kotlinx.coroutines.Job
13+
import kotlinx.coroutines.cancel
914
import kotlin.coroutines.CoroutineContext
1015

1116
class MainViewModel @ViewModelInject constructor(private var mainRepository: MainRepository) :
@@ -23,9 +28,13 @@ class MainViewModel @ViewModelInject constructor(private var mainRepository: Mai
2328
/**
2429
* Launch API using Coroutines
2530
*/
26-
fun fetchHerosList() {
27-
scope.launch {
28-
heroListLiveData.postValue(mainRepository.getHerosList())
31+
fun heroListLiveData() = liveData(coroutineContext) {
32+
emit(Resource.loading(data = null))
33+
try {
34+
emit(Resource.success(data = mainRepository.getHerosList()))
35+
} catch (e: Exception) {
36+
emit(Resource.error(data = null, message = e.message!!))
37+
e.printStackTrace()
2938
}
3039
}
3140

app/src/main/java/com/vimalvijay/mymodule/network/ApiConstants.kt renamed to app/src/main/java/com/vimalvijay/mymodule/network/api/ApiConstants.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.vimalvijay.mymodule.network
1+
package com.vimalvijay.mymodule.network.api
22

33
object ApiConstants {
44
const val BASE_URL = "https://simplifiedcoding.net/demos/"

0 commit comments

Comments
 (0)