Skip to content

Commit

Permalink
#91 검색 목록 저장/로드/삭제 하는 로직 제작, SearchHistoryDao, SearchHistoryDto, Sear…
Browse files Browse the repository at this point in the history
…chHistoryRepository, RoomDb, RoomModule등 Hilt로 의존성 주입, Room 라이브러리 의존성 추가, :core:database 모듈 추가
  • Loading branch information
pknujsp committed May 29, 2023
1 parent 77c0a82 commit bf49823
Show file tree
Hide file tree
Showing 26 changed files with 418 additions and 69 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ plugins {
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.nav.safeargs.kotlin) apply false
alias(libs.plugins.kapt) apply false
//alias(libs.plugins.ksp) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.kotlin.parcelize) apply false
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.android.mediproject.core.common.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder

/**
* 귀찮음 줄여주는 ListAdapter
*
* @param T : ListAdapter에 들어갈 아이템 타입
* @param V : ViewDataBinding
* @param differ : DiffUtil.ItemCallback<T>
* - ListAdapter의 DiffUtil.ItemCallback
* - 아이템이 같은지 비교하는 메소드를 구현해야함
* @param initViewHolder : (((CViewHolder<T, V>) -> Unit)
* - ViewHolder 초기화
* - ex) { holder -> ViewHolder class init 시 필요한 작업 처리 }
* @param onBind : (CViewHolder<T, V>, T, Int) -> Unit
* - ViewHolder 바인딩
* - ex) { holder, item, position -> 필요한 작업 처리 }
* @param itemViewId : Int
* - ViewHolder의 itemView id
* - ex) R.layout.item_view
*
*/
abstract class GodBindListAdapter<T, V : ViewDataBinding>(
differ: DiffUtil.ItemCallback<T>,
private val initViewHolder: ((GodBindViewHolder<T, V>) -> Unit)?,
private val onBind: (GodBindViewHolder<T, V>, T, Int) -> Unit,
@IdRes private val itemViewId: Int
) : ListAdapter<T, GodBindViewHolder<T, V>>(differ) {

private var _inflater: LayoutInflater? = null
private val inflater get() = _inflater!!

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
_inflater = null
_inflater = LayoutInflater.from(recyclerView.context)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GodBindViewHolder<T, V> =
GodBindViewHolder(DataBindingUtil.inflate<V>(inflater, itemViewId, parent, false), initViewHolder, onBind)


override fun onBindViewHolder(holder: GodBindViewHolder<T, V>, position: Int) {
holder.bind(getItem(position))
}

override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
_inflater = null
}
}

class GodBindViewHolder<T, V : ViewDataBinding>(
private val binding: V,
private val initViewHolder: ((GodBindViewHolder<T, V>) -> Unit)?,
private val onBind: (GodBindViewHolder<T, V>, T, Int) -> Unit,
) : ViewHolder(binding.root) {

init {
initViewHolder?.invoke(this)
}

fun bind(item: T) {
onBind.invoke(this, item, absoluteAdapterPosition)
binding.executePendingBindings()
}
}
1 change: 1 addition & 0 deletions core/data/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies {
implementation(project(":core:datastore"))
implementation(project(":core:model"))
implementation(project(":core:network"))
implementation(project(":core:database"))

implementation(libs.androidx.core.ktx)
implementation(libs.kotlinx.serialization.json)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.android.mediproject.core.data.remote.di

import com.android.mediproject.core.common.network.Dispatcher
import com.android.mediproject.core.common.network.MediDispatchers
import com.android.mediproject.core.data.remote.adminaction.AdminActionRepository
import com.android.mediproject.core.data.remote.adminaction.AdminActionRepositoryImpl
import com.android.mediproject.core.data.remote.comments.CommentsRepository
Expand All @@ -16,6 +18,9 @@ import com.android.mediproject.core.data.remote.recallsuspension.RecallSuspensio
import com.android.mediproject.core.data.remote.recallsuspension.RecallSuspensionRepositoryImpl
import com.android.mediproject.core.data.remote.sign.SignRepository
import com.android.mediproject.core.data.remote.sign.SignRepositoryImpl
import com.android.mediproject.core.data.search.SearchHistoryRepository
import com.android.mediproject.core.data.search.SearchHistoryRepositoryImpl
import com.android.mediproject.core.database.searchhistory.SearchHistoryDao
import com.android.mediproject.core.datastore.AppDataStore
import com.android.mediproject.core.datastore.TokenDataSourceImpl
import com.android.mediproject.core.network.datasource.comments.CommentsDataSource
Expand All @@ -31,6 +36,7 @@ import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Singleton

@InstallIn(SingletonComponent::class)
Expand All @@ -40,8 +46,10 @@ object RepositoryModule {
@Provides
@Singleton
fun provideMedicineApprovalRepository(
medicineApprovalDataSource: MedicineApprovalDataSource
): MedicineApprovalRepository = MedicineApprovalRepositoryImpl(medicineApprovalDataSource)
medicineApprovalDataSource: MedicineApprovalDataSource, searchHistoryDao: SearchHistoryDao
): MedicineApprovalRepository = MedicineApprovalRepositoryImpl(
medicineApprovalDataSource, searchHistoryDao
)

@Provides
@Singleton
Expand Down Expand Up @@ -81,4 +89,10 @@ object RepositoryModule {
fun providesSignRepository(
signDataSource: SignDataSource, connectionTokenDataSourceImpl: TokenDataSourceImpl, appDataStore: AppDataStore
): SignRepository = SignRepositoryImpl(signDataSource, connectionTokenDataSourceImpl, appDataStore)

@Provides
@Singleton
fun providesSearchHistoryRepository(
searchHistoryDao: SearchHistoryDao, @Dispatcher(MediDispatchers.IO) ioDispatcher: CoroutineDispatcher
): SearchHistoryRepository = SearchHistoryRepositoryImpl(searchHistoryDao, ioDispatcher)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.android.mediproject.core.common.DATA_GO_KR_PAGE_SIZE
import com.android.mediproject.core.database.searchhistory.SearchHistoryDao
import com.android.mediproject.core.model.medicine.medicineapproval.Item
import com.android.mediproject.core.model.medicine.medicinedetailinfo.MedicineDetailInfoResponse
import com.android.mediproject.core.network.datasource.medicineapproval.MedicineApprovalDataSource
Expand All @@ -15,8 +16,9 @@ import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class MedicineApprovalRepositoryImpl @Inject constructor(private val medicineApprovalDataSource: MedicineApprovalDataSource) :
MedicineApprovalRepository {
class MedicineApprovalRepositoryImpl @Inject constructor(
private val medicineApprovalDataSource: MedicineApprovalDataSource, private val searchHistoryDao: SearchHistoryDao
) : MedicineApprovalRepository {

/**
* PagingData를 사용하여 페이징 처리를 하기 위해 Pager를 사용
Expand All @@ -33,6 +35,7 @@ class MedicineApprovalRepositoryImpl @Inject constructor(private val medicineApp
if (itemName == null && entpName == null) {
emptyFlow()
} else {

Pager(config = PagingConfig(pageSize = DATA_GO_KR_PAGE_SIZE, prefetchDistance = 5), pagingSourceFactory = {
MedicineApprovalListDataSourceImpl(
medicineApprovalDataSource, itemName, entpName, medicationType
Expand All @@ -43,9 +46,7 @@ class MedicineApprovalRepositoryImpl @Inject constructor(private val medicineApp

override suspend fun getMedicineDetailInfo(itemName: String): Flow<Result<MedicineDetailInfoResponse.Body.Item>> = channelFlow {
medicineApprovalDataSource.getMedicineDetailInfo(itemName).map { result ->
result.fold(
onSuccess = { Result.success(it.body.items.first()) },
onFailure = { Result.failure(it) })
result.fold(onSuccess = { Result.success(it.body.items.first()) }, onFailure = { Result.failure(it) })
}.collectLatest {
send(it)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.android.mediproject.core.data.search

import com.android.mediproject.core.database.searchhistory.SearchHistoryDto
import kotlinx.coroutines.flow.Flow

interface SearchHistoryRepository {
suspend fun insertSearchHistory(query: String)

suspend fun getSearchHistoryList(count: Int = 5): Flow<List<SearchHistoryDto>>

suspend fun deleteSearchHistory(id: Long)

suspend fun deleteAllSearchHistory()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.android.mediproject.core.data.search

import com.android.mediproject.core.common.network.Dispatcher
import com.android.mediproject.core.common.network.MediDispatchers
import com.android.mediproject.core.database.searchhistory.SearchHistoryDao
import com.android.mediproject.core.database.searchhistory.SearchHistoryDto
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import javax.inject.Inject

class SearchHistoryRepositoryImpl @Inject constructor(
private val searchHistoryDao: SearchHistoryDao, @Dispatcher(MediDispatchers.IO) private val ioDispatcher: CoroutineDispatcher
) : SearchHistoryRepository {
override suspend fun insertSearchHistory(query: String) {
withContext(ioDispatcher) {
searchHistoryDao.insert(
SearchHistoryDto(
query = query, id = 0L, searchDateTime = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)
)
)
}
}

override suspend fun getSearchHistoryList(count: Int): Flow<List<SearchHistoryDto>> = withContext(ioDispatcher) {
searchHistoryDao.select(count)
}


override suspend fun deleteSearchHistory(id: Long) {
withContext(ioDispatcher) {
searchHistoryDao.delete(id)
}
}

override suspend fun deleteAllSearchHistory() {
withContext(ioDispatcher) {
searchHistoryDao.deleteAll()
}
}

}
1 change: 1 addition & 0 deletions core/database/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
21 changes: 21 additions & 0 deletions core/database/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
plugins {
id("mediproject.android.library")
id("mediproject.android.hilt")
alias(libs.plugins.ksp)
}

android {
namespace = "com.android.mediproject.core.database"

buildFeatures {
buildConfig = true
}
}

dependencies {
implementation(project(":core:common"))
implementation(project(":core:model"))

implementation(libs.bundles.rooms)
implementation(libs.kotlinx.coroutines.android)
}
Empty file.
21 changes: 21 additions & 0 deletions core/database/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.android.mediproject.core.database

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.android.mediproject.core.database.test", appContext.packageName)
}
}
4 changes: 4 additions & 0 deletions core/database/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.android.mediproject.core.database

import androidx.room.Database
import androidx.room.RoomDatabase
import com.android.mediproject.core.database.searchhistory.SearchHistoryDao
import com.android.mediproject.core.database.searchhistory.SearchHistoryDto


@Database(entities = [SearchHistoryDto::class], version = 1)
abstract class RoomDb : RoomDatabase() {
abstract fun searchHistoryDao(): SearchHistoryDao
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.android.mediproject.core.database

import android.content.Context
import androidx.room.Room
import com.android.mediproject.core.database.searchhistory.SearchHistoryDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

@Module(includes = [DaoModule::class])
@InstallIn(SingletonComponent::class)
object RoomModule {

@Provides
@Singleton
fun provideRoomDb(@ApplicationContext context: Context): RoomDb = Room.databaseBuilder(
context, RoomDb::class.java, "medi_database"
).build()
}


@Module
@InstallIn(SingletonComponent::class)
object DaoModule {
@Provides
fun provideSearchHistoryDao(roomDb: RoomDb): SearchHistoryDao = roomDb.searchHistoryDao()
}
Loading

0 comments on commit bf49823

Please sign in to comment.