Skip to content

Commit

Permalink
feat: state flow retrofit and db extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
CraZyLegenD committed Nov 13, 2020
1 parent 75e383d commit d9dcc12
Show file tree
Hide file tree
Showing 8 changed files with 561 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import android.view.Menu
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.Fade
import androidx.transition.Transition
import androidx.transition.TransitionListenerAdapter
import androidx.transition.TransitionManager
import com.crazylegend.biometrics.biometricAuth
import com.crazylegend.biometrics.canAuthenticate
import com.crazylegend.customviews.AppRater
import com.crazylegend.customviews.autoStart.AutoStartHelper
import com.crazylegend.customviews.autoStart.ConfirmationDialogAutoStart
Expand Down Expand Up @@ -42,6 +41,8 @@ import com.crazylegend.setofusefulkotlinextensions.adapter.TestViewHolderShimmer
import com.crazylegend.setofusefulkotlinextensions.databinding.ActivityMainBinding
import com.crazylegend.viewbinding.viewBinding
import io.reactivex.rxjava3.disposables.CompositeDisposable
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File

class MainAbstractActivity : AppCompatActivity() {
Expand Down Expand Up @@ -99,7 +100,8 @@ class MainAbstractActivity : AppCompatActivity() {
debug("SECURITY isEmulator ${isEmulator()}")
debug("SECURITY getShaSignature ${getShaSignature(BuildConfig.APPLICATION_ID)}")

canAuthenticate(hardwareUnavailable = {

/*canAuthenticate(hardwareUnavailable = {
//some message about hardware missing
}, noFingerprintsEnrolled = {
//make user action to enroll fingerprints
Expand All @@ -118,10 +120,14 @@ class MainAbstractActivity : AppCompatActivity() {
}) {
//handle successful authentication
}
}
}*/

activityMainBinding.test.setOnClickListener {
testAVM.getposts()
lifecycleScope.launch {
testAVM.getposts().collect {
updateUI(it)
}
}
}

RunCodeEveryXLaunchOnAppOpened.runCode(this, 2) {
Expand Down Expand Up @@ -170,39 +176,12 @@ class MainAbstractActivity : AppCompatActivity() {
EdgeToEdge.setUpScrollingContent(activityMainBinding.recycler)
}

val stagger = StaggerTransition()

testAVM.posts.observe(this, {
it?.apply {
when (it) {
is RetrofitResult.Success -> {
TransitionManager.beginDelayedTransition(activityMainBinding.recycler, stagger)
if (activityMainBinding.recycler.adapter != generatedAdapter) {
activityMainBinding.recycler.adapter = generatedAdapter
savedItemAnimator = activityMainBinding.recycler.itemAnimator
activityMainBinding.recycler.itemAnimator = null
TransitionManager.beginDelayedTransition(activityMainBinding.recycler, fade)
}
generatedAdapter.submitList(it.value)
val wrappedList = it.value.toMutableList()
activityMainBinding.recycler.addDrag(generatedAdapter, wrappedList)
}
RetrofitResult.Loading -> {
activityMainBinding.recycler.adapter = testPlaceHolderAdapter
}
RetrofitResult.EmptyData -> {
}
is RetrofitResult.Error -> {
}
is RetrofitResult.ApiError -> {
}
}.exhaustive
lifecycleScope.launchWhenResumed {
testAVM.apiTestState.collect {
updateUI(it)
}
})
}

testAVM.filteredPosts.observe(this, {
generatedAdapter.submitList(it)
})

val testFile = File(filesDir, "testfile.txt")
encryptFileSafely(testFile, fileContent = "JETPACK SECURITY".toByteArray())
Expand All @@ -211,6 +190,34 @@ class MainAbstractActivity : AppCompatActivity() {
debug("TEXT ENCRYPTED ${testFile.readText()}")
}

private fun updateUI(retrofitResult: RetrofitResult<List<TestModel>>) {
val stagger = StaggerTransition()

when (retrofitResult) {
is RetrofitResult.Success -> {
TransitionManager.beginDelayedTransition(activityMainBinding.recycler, stagger)
if (activityMainBinding.recycler.adapter != generatedAdapter) {
activityMainBinding.recycler.adapter = generatedAdapter
savedItemAnimator = activityMainBinding.recycler.itemAnimator
activityMainBinding.recycler.itemAnimator = null
TransitionManager.beginDelayedTransition(activityMainBinding.recycler, fade)
}
generatedAdapter.submitList(retrofitResult.value)
val wrappedList = retrofitResult.value.toMutableList()
activityMainBinding.recycler.addDrag(generatedAdapter, wrappedList)
}
RetrofitResult.Loading -> {
activityMainBinding.recycler.adapter = testPlaceHolderAdapter
}
RetrofitResult.EmptyData -> {
}
is RetrofitResult.Error -> {
}
is RetrofitResult.ApiError -> {
}
}.exhaustive
}

private var searchView: SearchView? = null

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package com.crazylegend.setofusefulkotlinextensions

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.*
import com.crazylegend.retrofit.RetrofitClient
import com.crazylegend.retrofit.coroutines.makeApiCallLiveData
import com.crazylegend.retrofit.coroutines.apiCallStateFlow
import com.crazylegend.retrofit.retrofitResult.RetrofitResult
import com.crazylegend.retrofit.retrofitResult.getSuccess
import com.crazylegend.rx.clearAndDispose
Expand All @@ -33,10 +30,10 @@ class TestAVM(application: Application, testModel: TestModel, key: Int, string:

private val compositeDisposable = CompositeDisposable()

fun getposts() {
//val apiTest = apiCallAsFlow { retrofit.getPosts() }
val apiTestState = getposts()

makeApiCallLiveData(postsData) { retrofit.getPosts() }
}
fun getposts() = viewModelScope.apiCallStateFlow { retrofit.getPosts() }

fun filterBy(query: String) {
filteredPostsData.value = postsData.getSuccess?.filter {
Expand All @@ -55,7 +52,7 @@ class TestAVM(application: Application, testModel: TestModel, key: Int, string:
}

init {
getposts()
// getposts()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.crazylegend.database

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.flow.MutableStateFlow


/**
Expand Down Expand Up @@ -224,4 +225,62 @@ inline val <T> LiveData<DBResult<T>>.getSuccess: T?
}

internal inline fun <T, R> T.isListAndNotNullOrEmpty(actionFalse: () -> R, actionTrue: () -> R): R =
if (this is List<*> && !this.isNullOrEmpty()) actionTrue() else actionFalse()
if (this is List<*> && !this.isNullOrEmpty()) actionTrue() else actionFalse()


fun <T> MutableStateFlow<DBResult<T>>.querying() {
value = databaseQuerying
}


fun <T> MutableStateFlow<DBResult<T>>.emptyData() {
value = databaseEmptyDB
}


fun <T> MutableStateFlow<DBResult<T>>.subscribe(queryModel: T?, includeEmptyData: Boolean = false) {
if (includeEmptyData) {
if (queryModel == null) {
value = databaseEmptyDB
} else {
value = databaseSuccess(queryModel)
}
} else {
queryModel?.apply {
value = databaseSuccess(this)
}
}
}


fun <T> MutableStateFlow<DBResult<T>>.subscribeList(queryModel: T?, includeEmptyData: Boolean = false) {
if (includeEmptyData) {
if (queryModel == null) {
value = databaseEmptyDB
} else {
if (this is List<*>) {
val list = this as List<*>
if (list.isNullOrEmpty()) {
value = databaseEmptyDB
} else {
value = databaseSuccess(queryModel)
}
} else {
value = databaseSuccess(queryModel)
}
}
} else {
queryModel?.apply {
value = databaseSuccess(this)
}
}
}


fun <T> MutableStateFlow<DBResult<T>>.callError(throwable: Throwable) {
value = databaseError(throwable)
}

fun <T> MutableStateFlow<DBResult<T>>.success(model: T) {
value = databaseSuccess(model)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import com.crazylegend.database.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onStart
import kotlin.coroutines.CoroutineContext


Expand Down Expand Up @@ -225,7 +227,7 @@ inline fun <T> CoroutineScope.makeDBCallListAsync(
}


inline fun <T> AndroidViewModel.makeDBCallListAsync(
inline fun <T> ViewModel.makeDBCallListAsync(
dbResult: MutableLiveData<DBResult<T>>,
includeEmptyData: Boolean = true,
crossinline dbCall: suspend () -> T?): Job {
Expand All @@ -245,7 +247,7 @@ inline fun <T> AndroidViewModel.makeDBCallListAsync(
}


inline fun <T> AndroidViewModel.makeDBCallAsync(
inline fun <T> ViewModel.makeDBCallAsync(
dbResult: MutableLiveData<DBResult<T>>,
includeEmptyData: Boolean = false,
crossinline dbCall: suspend () -> T?): Job {
Expand Down Expand Up @@ -601,3 +603,13 @@ fun <T> CoroutineScope.makeDBCallFlow(
}
}

fun <T> dbCallAsFlow(apiCall: suspend () -> T?): Flow<DBResult<T>> =
flow {
try {
emit(databaseSubscribe(apiCall.invoke()))
} catch (t: Throwable) {
emit(databaseError(t))
}
}.onStart {
emit(databaseQuerying)
}
Loading

0 comments on commit d9dcc12

Please sign in to comment.