1+ package com.github.htdangkhoa.cleanarchitecture.base
2+
3+ import android.app.Activity
4+ import android.os.Bundle
5+ import android.view.LayoutInflater
6+ import android.view.View
7+ import android.view.ViewGroup
8+ import androidx.annotation.CallSuper
9+ import androidx.annotation.LayoutRes
10+ import androidx.fragment.app.Fragment
11+ import androidx.lifecycle.ViewModel
12+ import com.afollestad.materialdialogs.MaterialDialog
13+ import com.github.htdangkhoa.cleanarchitecture.data.model.AuthModel
14+ import com.github.htdangkhoa.cleanarchitecture.data.model.ResponseExceptionModel
15+ import com.github.htdangkhoa.cleanarchitecture.ui.login.LoginActivity
16+ import com.pawegio.kandroid.startActivity
17+ import org.koin.androidx.viewmodel.ext.android.sharedViewModel
18+ import retrofit2.HttpException
19+ import kotlin.reflect.KClass
20+
21+ abstract class BaseFragmentSharedViewModel <VM : ViewModel , A : BaseActivity <VM >>(
22+ clazz : KClass <VM >
23+ ): Fragment() {
24+ @get:LayoutRes
25+ abstract val layoutResID: Int
26+
27+ protected val viewModel: VM by sharedViewModel(clazz)
28+
29+ override fun onCreateView (
30+ inflater : LayoutInflater ,
31+ container : ViewGroup ? ,
32+ savedInstanceState : Bundle ?
33+ ): View ? {
34+ return inflater.inflate(layoutResID, container, false )
35+ }
36+
37+ @CallSuper
38+ override fun onViewCreated (view : View , savedInstanceState : Bundle ? ) {
39+ render(view, savedInstanceState)
40+ }
41+
42+ protected open fun render (view : View , savedInstanceState : Bundle ? ) = Unit
43+
44+ protected fun handleError (throwable : Throwable ? = null, block : ((Throwable ? ) -> Unit )? = null) {
45+ return block?.invoke(throwable) ? : handleHttpError(throwable)
46+ }
47+
48+ protected fun handleHttpError (throwable : Throwable ? ) {
49+ when (throwable) {
50+ is HttpException -> {
51+ logout(throwable.code())
52+ }
53+ is ResponseExceptionModel -> {
54+ throwable.responseModel?.code?.let { logout(it) }
55+ }
56+ }
57+ }
58+
59+ protected fun logout (code : Int ) {
60+ if (code == 401 ) {
61+ AuthModel .clear()
62+
63+ context?.let {
64+ if (it is Activity && it::class .simpleName != LoginActivity ::class .simpleName) {
65+ it.startActivity<LoginActivity >()
66+
67+ it.finishAfterTransition()
68+ }
69+ }
70+ }
71+ }
72+
73+ protected fun showDialog (title : String? = "Info ", message : String? = null): MaterialDialog {
74+ return MaterialDialog (context!! ).show {
75+ title(text = title)
76+
77+ message(text = message)
78+
79+ positiveButton(text = " OK" )
80+ }
81+ }
82+ }
0 commit comments