fix: Task 13 완료 - TaskAggregator/WorkersDb 예외 처리 및 RssHome viewLifecycleOwner 스코프 전환

- TaskAggregator.kt:
  * SupervisorJob 기반 공유 aggregatorScope 도입
  * refreshSystemInfo(), refreshNewsFeeds() 전체 try-catch 보강 및 개별 피드 수집기를 runCatching으로 격리해 단일 사이트 실패가 전체 피드 수집을 중단하지 않도록 개선
- RssHome.kt:
  * updateQuery() 및 스와이프 DB 갱신 코루틴을 viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO)로 전환, 불필요한 infosJob?.start() 제거 및 Realm writeBlocking 예외 방어 추가
- WorkersDb.kt:
  * insertExpressions() writeBlocking 트랜잭션에 try-catch 및 에러 로깅 추가
- TODO.md: 2-4, 3-3 항목 완료 처리
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (3s)
This commit is contained in:
2026-11-16 11:40:45 +09:00
parent 6b36757337
commit 90ad54ac53
4 changed files with 51 additions and 32 deletions
@@ -41,6 +41,7 @@ import androidx.annotation.NonNull
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
@@ -801,7 +802,8 @@ internal class RssHome : RemoteGestureFragment() , KeyEventHandler {
mLastedQuery = q.query("hide != $0", true).sort("pubDate ", Sort.DESCENDING).limit(500).distinct("originPage", "title")
mRssDataResult = mLastedQuery?.find()
mRssDataResult?.asFlow()?.let { flow ->
infosJob = CoroutineScope(Dispatchers.IO).launch {
if (view == null) return@let
infosJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
flow.collect { changes: ResultsChange<RssData> ->
synchronized(lasted) {
commandHandler.removeCallbacks(infoUpdate)
@@ -813,7 +815,6 @@ internal class RssHome : RemoteGestureFragment() , KeyEventHandler {
}
}
}
infosJob?.start()
}
}
@@ -944,7 +945,9 @@ internal class RssHome : RemoteGestureFragment() , KeyEventHandler {
) {
Blog.LOGE("onSwiped direction >>>> $direction")
(viewHolder.itemView.tag as? RssData)?.let { rssD : RssData ->
CoroutineScope(Dispatchers.IO).launch {
if (view == null) return@let
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
try {
val rss : RssData = rssD
WorkersDb.getRealm().apply {
writeBlocking {
@@ -981,6 +984,9 @@ internal class RssHome : RemoteGestureFragment() , KeyEventHandler {
binding.infoList.post { mRssAdapter.refresh() }
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
@@ -9,12 +9,14 @@ import io.realm.kotlin.UpdatePolicy
import kotlinx.coroutines.*
object TaskAggregator {
private val aggregatorScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
// 1. 시스템 정보 통합 업데이트 (App, Contact, SMS 등)
// 로컬 작업이므로 Dispatchers.Default 사용
fun refreshSystemInfo(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
val startTime = System.currentTimeMillis()
aggregatorScope.launch {
try {
val startTime = System.currentTimeMillis()
// 1. [병렬 수집] 시스템에서 최신 데이터 가져오기 (이때 카운트는 0인 상태)
val appsJob = async { AppInfoGetter(context).fetchData() }
@@ -82,43 +84,50 @@ object TaskAggregator {
}
Blog.LOGE("SystemInfo Aggregation finished in ${System.currentTimeMillis() - startTime}ms.")
} catch (e: Exception) {
Blog.LOGE("SystemInfo Aggregation failed: ${e.message}")
}
}
}
// 2. 뉴스 피드 통합 업데이트 (Ruliweb, Youtube, FMKorea 등)
// 네트워크 작업이므로 Dispatchers.IO 사용
fun refreshNewsFeeds(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
val startTime = System.currentTimeMillis()
aggregatorScope.launch {
try {
val startTime = System.currentTimeMillis()
// 병렬로 네트워크 요청 쏘기 (시간 획기적으로 단축됨)
val jobs = listOf(
async { TheQooGetter(context).fetchData() },
async { DCGetter(context).fetchData() },
async { NewsFeedsGetter(context).fetchData() },
async { ClienGetter(context).fetchData() },
async { DotaxGetter(context).fetchData() },
async { RedditGetter(context).fetchData() },
)
// 병렬로 네트워크 요청 쏘기 (개별 실패가 전체 수집을 중단하지 않도록 격리)
val jobs = listOf(
async { runCatching { TheQooGetter(context).fetchData() }.getOrElse { emptyList() } },
async { runCatching { DCGetter(context).fetchData() }.getOrElse { emptyList() } },
async { runCatching { NewsFeedsGetter(context).fetchData() }.getOrElse { emptyList() } },
async { runCatching { ClienGetter(context).fetchData() }.getOrElse { emptyList() } },
async { runCatching { DotaxGetter(context).fetchData() }.getOrElse { emptyList() } },
async { runCatching { RedditGetter(context).fetchData() }.getOrElse { emptyList() } },
)
// 결과 수집
val allFeeds = jobs.awaitAll().flatten()
// [일괄 저장]
if (allFeeds.isNotEmpty()) {
try {
WorkersDb.getRealm().write {
// 1. 새 데이터 저장
allFeeds.forEach { feed ->
try { copyToRealm(feed, UpdatePolicy.ERROR) }catch (e: Exception){}
// 결과 수집
val allFeeds = jobs.awaitAll().flatten()
// [일괄 저장]
if (allFeeds.isNotEmpty()) {
try {
WorkersDb.getRealm().write {
// 1. 새 데이터 저장
allFeeds.forEach { feed ->
try { copyToRealm(feed, UpdatePolicy.ERROR) } catch (_: Exception) {}
}
}
} catch (e: Exception) {
Blog.LOGE("NewsFeed Realm write failed: ${e.message}")
}
}catch (e: Exception){}
}
Blog.LOGE("NewsFeed Aggregation finished in ${System.currentTimeMillis() - startTime}ms. Items: ${allFeeds.size}")
} catch (e: Exception) {
Blog.LOGE("NewsFeed Aggregation failed: ${e.message}")
}
Blog.LOGE("NewsFeed Aggregation finished in ${System.currentTimeMillis() - startTime}ms. Items: ${allFeeds.size}")
}
}
}
@@ -86,7 +86,8 @@ object WorkersDb {
fun insertExpressions(groups: List<WallContentGroup>) {
getRealm().writeBlocking {
try {
getRealm().writeBlocking {
groups.forEach { group ->
group.translations.forEach { trans ->
@@ -115,6 +116,9 @@ object WorkersDb {
}
}
}
} catch (e: Exception) {
Blog.LOGE("insertExpressions error: ${e.message}")
}
}
// [추가] 앱/연락처 사용 시 로그 저장 (기존 updateAppUse 대신 이거 호출)