diff --git a/TODO.md b/TODO.md index 2b23b03a..76c4425a 100644 --- a/TODO.md +++ b/TODO.md @@ -84,7 +84,7 @@ - `app/src/main/kotlin/bums/lunatic/launcher/helpers/ForeGroundService.kt:426, 542-598` — `companion object`의 `targetUrls`(일반 `ArrayList`)와 `lastProGress`, `currentProcessId`가 여러 `CoroutineScope(Dispatchers.IO)`에서 동기화 없이 접근/수정됨. - **작업**: `Channel` 또는 `Mutex` 기반 순차 다운로드 큐로 전환하고, `targetUrls`를 스레드 안전 구조로 교체. -- [ ] **2-4. `RssHome` Realm Flow 수집과 UI 리스트 동기화 정리** +- [x] **2-4. `RssHome` Realm Flow 수집과 UI 리스트 동기화 정리** - `app/src/main/kotlin/bums/lunatic/launcher/home/RssHome.kt:804-817` — `CoroutineScope(Dispatchers.IO)`에서 `synchronized(lasted)` 블록 안에서 `WorkersDb.getRealm()`으로 `copyFromRealm()` 후 `commandHandler.post(infoUpdate)` 호출. `infosJob?.start()`는 `launch` 직후 불필요한 호출이며, Fragment `onDestroyView()` 시 `infosJob` 취소 및 `lasted` 접근 동기화 일원화 필요. --- @@ -101,7 +101,7 @@ - `app/src/main/kotlin/bums/lunatic/launcher/workers/LocationUpdateService.kt:50-52` — `geocoder.getFromLocation(...) { addresses -> addresses.first()?.let { ... } }`에서 `addresses`가 빈 리스트일 경우 `NoSuchElementException` 발생 가능 (`105`, `127`행에서도 `addresses.first()` 재호출). - **작업**: `addresses.firstOrNull()?.let { address -> ... }`로 변경하고 단일 변수 `address` 재사용. -- [ ] **3-3. `WorkersDb` 및 `TaskAggregator` Realm 트랜잭션 예외 처리** +- [x] **3-3. `WorkersDb` 및 `TaskAggregator` Realm 트랜잭션 예외 처리** - `app/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt:88-160` — `writeBlocking` 호출 시 예외 처리가 없어 DB 잠금/마이그레이션/스키마 오류 시 크래시 위험. - `app/src/main/kotlin/bums/lunatic/launcher/workers/TaskAggregator.kt:16-55` — `CoroutineScope(Dispatchers.IO).launch` 내부에 `try-catch`가 없어 `AppInfoGetter`/`ContactInfoGetter` 또는 `realm.write` 실패 시 조용히 실패하거나 앱 크래시 유발. - **작업**: `TaskAggregator`에 `try-catch` 및 실패 로깅 추가, 메인 스레드에서의 `writeBlocking` 호출 여부 점검 후 비동기 `write`로 전환. diff --git a/app/src/main/kotlin/bums/lunatic/launcher/home/RssHome.kt b/app/src/main/kotlin/bums/lunatic/launcher/home/RssHome.kt index e2193c53..8b972287 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/home/RssHome.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/home/RssHome.kt @@ -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 -> 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() + } } } } diff --git a/app/src/main/kotlin/bums/lunatic/launcher/workers/TaskAggregator.kt b/app/src/main/kotlin/bums/lunatic/launcher/workers/TaskAggregator.kt index a4cc6fc7..dc431842 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/workers/TaskAggregator.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/workers/TaskAggregator.kt @@ -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}") } } } \ No newline at end of file diff --git a/app/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt b/app/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt index fccd0e83..81ad9427 100644 --- a/app/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt +++ b/app/src/main/kotlin/bums/lunatic/launcher/workers/WorkersDb.kt @@ -86,7 +86,8 @@ object WorkersDb { fun insertExpressions(groups: List) { - 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 대신 이거 호출)