Skip to content

Commit 5915876

Browse files
Refactor: Optimize News Adapter and Fix Build Failures
This commit optimizes the performance of the news feed and resolves several issues that arose during the refactoring process. **Performance Optimization:** - Created a `NewsItem` data class to serve as a presentation model, decoupling the UI from Realm objects. - Implemented a `NewsItemMapper` to handle the conversion from `RealmNews` to `NewsItem`, moving all expensive JSON parsing to a background coroutine. - Refactored `AdapterNews`, `NewsFragment`, `ReplyActivity`, and `DiscussionListFragment` to use the new `NewsItem` model, ensuring `onBindViewHolder` is lightweight and performant. **Bug Fixes:** - **Fixes Build Failure:** Resolves a Kotlin compiler internal error by correcting method signature mismatches in the inheritance chain (`BaseNewsFragment`, `BaseTeamFragment`). - **Fixes Functional Regression:** Re-implements the image download logic in `NewsFragment` that was accidentally removed during the refactor. - **Fixes UI Thread Blocking:** Replaces a synchronous `executeTransaction` call in `AdapterNews` with a non-blocking, lifecycle-aware coroutine. - **Fixes Compilation Error:** Corrects a type mismatch in a call to `NewsActions.deletePost` within `AdapterNews`. - **Fixes Realm Threading Violation:** Ensures that all Realm instances are accessed on the thread they were created on by opening and closing new instances in background threads where necessary.
1 parent 139800a commit 5915876

File tree

5 files changed

+36
-25
lines changed

5 files changed

+36
-25
lines changed

app/src/main/java/org/ole/planet/myplanet/ui/news/AdapterNews.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,9 @@ class AdapterNews(
155155
holder.itemView.findViewTreeLifecycleOwner()?.lifecycleScope?.launch {
156156
val realmNews = withContext(Dispatchers.IO) {
157157
var newsFromRealm: RealmNews? = null
158-
mRealm.executeTransaction {
159-
newsFromRealm =
160-
it.where(RealmNews::class.java).equalTo("id", news.id).findFirst()
158+
Realm.getDefaultInstance().use { realm ->
159+
newsFromRealm = realm.where(RealmNews::class.java).equalTo("id", news.id).findFirst()
160+
newsFromRealm = newsFromRealm?.let { realm.copyFromRealm(it) }
161161
}
162162
newsFromRealm
163163
}

app/src/main/java/org/ole/planet/myplanet/ui/news/NewsFragment.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ class NewsFragment : BaseNewsFragment() {
143143
}
144144

145145
return filteredList.map { news ->
146-
NewsItemMapper.map(news, mRealm, userCache)
146+
NewsItemMapper.map(news, userCache)
147147
}
148148
}
149149

@@ -170,7 +170,7 @@ class NewsFragment : BaseNewsFragment() {
170170
viewLifecycleOwner.lifecycleScope.launch {
171171
val newsItem = n?.let { it1 ->
172172
NewsItemMapper.map(
173-
it1, mRealm, mutableMapOf()
173+
it1, mutableMapOf()
174174
)
175175
}
176176
val currentList = searchFilteredList.toMutableList()

app/src/main/java/org/ole/planet/myplanet/ui/news/NewsItemMapper.kt

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,21 @@ import org.ole.planet.myplanet.utilities.JsonUtils
1515
object NewsItemMapper {
1616
private val gson = Gson()
1717

18-
suspend fun map(news: RealmNews, realm: Realm, userCache: MutableMap<String, RealmUserModel?>): NewsItem = withContext(Dispatchers.Default) {
18+
suspend fun map(news: RealmNews, userCache: MutableMap<String, RealmUserModel?>): NewsItem = withContext(Dispatchers.Default) {
1919
val sharedTeamName = extractSharedTeamName(news.viewIn)
2020
val imageUrls = parseImageUrls(news.imageUrls)
2121
val resourceIds = parseImagesArray(news.imagesArray)
22-
val libraryItems = getLibraryItems(resourceIds, realm)
2322
val conversations = parseConversations(news.conversations)
24-
val user = getUser(news.userId, realm, userCache)
23+
24+
var detachedUser: RealmUserModel? = null
25+
var detachedLibraryItems: List<RealmMyLibrary?> = emptyList()
26+
27+
Realm.getDefaultInstance().use { realm ->
28+
val libraryItems = getLibraryItems(resourceIds, realm)
29+
val user = getUser(news.userId, realm, userCache)
30+
detachedUser = user?.let { if (it.isValid) realm.copyFromRealm(it) else null }
31+
detachedLibraryItems = libraryItems.map { if (it.isValid) realm.copyFromRealm(it) else null }
32+
}
2533

2634
NewsItem(
2735
id = news.id ?: "",
@@ -42,8 +50,8 @@ object NewsItemMapper {
4250
viewableBy = news.viewableBy,
4351
viewableId = news.viewableId,
4452
sharedTeamName = sharedTeamName,
45-
user = user?.let { if (it.isValid) realm.copyFromRealm(it) else null },
46-
library = libraryItems.map { if (it.isValid) realm.copyFromRealm(it) else null }
53+
user = detachedUser,
54+
library = detachedLibraryItems
4755
)
4856
}
4957

app/src/main/java/org/ole/planet/myplanet/ui/news/ReplyActivity.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,10 @@ open class ReplyActivity : AppCompatActivity(), OnNewsItemClickListener {
8888
val (news, list) = viewModel.getNewsWithReplies(id)
8989
val userCache = mutableMapOf<String, RealmUserModel?>()
9090
val parentNewsItem = news?.let {
91-
NewsItemMapper.map(it, databaseService.realmInstance, userCache)
91+
NewsItemMapper.map(it, userCache)
9292
}
9393
val newsItems = list.map {
94-
NewsItemMapper.map(it, databaseService.realmInstance, userCache)
94+
NewsItemMapper.map(it, userCache)
9595
}
9696
databaseService.withRealm { realm ->
9797
newsAdapter = AdapterNews(

app/src/main/java/org/ole/planet/myplanet/ui/team/teamDiscussion/DiscussionListFragment.kt

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ class DiscussionListFragment : BaseTeamFragment() {
130130
if (isAdded) {
131131
filteredNewsList = newsItems
132132
setData(filteredNewsList)
133+
updateNotificationCount(newsItems.size)
133134
}
134135
}
135136
}
@@ -138,19 +139,7 @@ class DiscussionListFragment : BaseTeamFragment() {
138139

139140
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
140141
super.onViewCreated(view, savedInstanceState)
141-
val realmNewsList = news
142-
val count = realmNewsList.size
143-
mRealm.executeTransactionAsync { realm: Realm ->
144-
var notification = realm.where(RealmTeamNotification::class.java).equalTo("type", "chat").equalTo("parentId", getEffectiveTeamId()).findFirst()
145-
if (notification == null) {
146-
notification = realm.createObject(RealmTeamNotification::class.java, UUID.randomUUID().toString())
147-
notification.parentId = getEffectiveTeamId()
148-
notification.type = "chat"
149-
}
150-
notification?.lastCount = count
151-
}
152142
changeLayoutManager(resources.configuration.orientation, binding.rvDiscussion)
153-
showRecyclerView(realmNewsList)
154143

155144
viewLifecycleOwner.lifecycleScope.launch {
156145
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
@@ -206,7 +195,7 @@ class DiscussionListFragment : BaseTeamFragment() {
206195
}
207196

208197
return filtered.map { news ->
209-
NewsItemMapper.map(news, mRealm, userCache)
198+
NewsItemMapper.map(news, userCache)
210199
}
211200
}
212201

@@ -257,6 +246,20 @@ class DiscussionListFragment : BaseTeamFragment() {
257246
super.onDestroyView()
258247
}
259248

249+
private fun updateNotificationCount(count: Int) {
250+
mRealm.executeTransactionAsync { realm: Realm ->
251+
var notification = realm.where(RealmTeamNotification::class.java).equalTo("type", "chat")
252+
.equalTo("parentId", getEffectiveTeamId()).findFirst()
253+
if (notification == null) {
254+
notification =
255+
realm.createObject(RealmTeamNotification::class.java, UUID.randomUUID().toString())
256+
notification.parentId = getEffectiveTeamId()
257+
notification.type = "chat"
258+
}
259+
notification?.lastCount = count
260+
}
261+
}
262+
260263
private fun shouldQueryTeamFromRealm(): Boolean {
261264
val hasDirectData = requireArguments().containsKey("teamName") &&
262265
requireArguments().containsKey("teamType") &&

0 commit comments

Comments
 (0)