Realm: remove RealmLiveData and use Optional for LiveData with potential null value

This commit is contained in:
ganfra 2019-10-03 19:19:53 +02:00
parent 525da17678
commit ef2af14529
18 changed files with 103 additions and 128 deletions

View File

@ -0,0 +1,10 @@
package im.vector.matrix.rx
import im.vector.matrix.android.api.util.Optional
import io.reactivex.Observable
fun <T : Any> Observable<Optional<T>>.unwrap(): Observable<T> {
return this
.filter { it.hasValue() }
.map { it.get() }
}

View File

@ -28,7 +28,7 @@ import io.reactivex.Single
class RxRoom(private val room: Room) {
fun liveRoomSummary(): Observable<RoomSummary> {
fun liveRoomSummary(): Observable<Optional<RoomSummary>> {
return room.getRoomSummaryLive().asObservable()
}
@ -36,11 +36,11 @@ class RxRoom(private val room: Room) {
return room.getRoomMemberIdsLive().asObservable()
}
fun liveAnnotationSummary(eventId: String): Observable<EventAnnotationsSummary> {
fun liveAnnotationSummary(eventId: String): Observable<Optional<EventAnnotationsSummary>> {
return room.getEventSummaryLive(eventId).asObservable()
}
fun liveTimelineEvent(eventId: String): Observable<TimelineEvent> {
fun liveTimelineEvent(eventId: String): Observable<Optional<TimelineEvent>> {
return room.getTimeLineEventLive(eventId).asObservable()
}

View File

@ -26,6 +26,7 @@ import im.vector.matrix.android.api.session.room.send.DraftService
import im.vector.matrix.android.api.session.room.send.SendService
import im.vector.matrix.android.api.session.room.state.StateService
import im.vector.matrix.android.api.session.room.timeline.TimelineService
import im.vector.matrix.android.api.util.Optional
/**
* This interface defines methods to interact within a room.
@ -49,7 +50,7 @@ interface Room :
* A live [RoomSummary] associated with the room
* You can observe this summary to get dynamic data from this room.
*/
fun getRoomSummaryLive(): LiveData<RoomSummary>
fun getRoomSummaryLive(): LiveData<Optional<RoomSummary>>
fun roomSummary(): RoomSummary?

View File

@ -21,6 +21,7 @@ import im.vector.matrix.android.api.session.events.model.Event
import im.vector.matrix.android.api.session.room.model.EventAnnotationsSummary
import im.vector.matrix.android.api.session.room.timeline.TimelineEvent
import im.vector.matrix.android.api.util.Cancelable
import im.vector.matrix.android.api.util.Optional
/**
* In some cases, events may wish to reference other events.
@ -111,7 +112,7 @@ interface RelationService {
replyText: String,
autoMarkdown: Boolean = false): Cancelable?
fun getEventSummaryLive(eventId: String): LiveData<EventAnnotationsSummary>
fun getEventSummaryLive(eventId: String): LiveData<Optional<EventAnnotationsSummary>>
}

View File

@ -17,6 +17,7 @@
package im.vector.matrix.android.api.session.room.timeline
import androidx.lifecycle.LiveData
import im.vector.matrix.android.api.util.Optional
/**
* This interface defines methods to interact with the timeline. It's implemented at the room level.
@ -36,5 +37,5 @@ interface TimelineService {
fun getTimeLineEvent(eventId: String): TimelineEvent?
fun getTimeLineEventLive(eventId: String): LiveData<TimelineEvent>
fun getTimeLineEventLive(eventId: String): LiveData<Optional<TimelineEvent>>
}

View File

@ -31,6 +31,10 @@ data class Optional<T : Any> constructor(private val value: T?) {
return value ?: fn()
}
fun hasValue(): Boolean{
return value != null
}
companion object {
fun <T : Any> from(value: T?): Optional<T> {
return Optional(value)

View File

@ -1,46 +0,0 @@
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.database
import androidx.lifecycle.LiveData
import io.realm.*
class RealmLiveData<T : RealmModel>(private val realmConfiguration: RealmConfiguration,
private val query: (Realm) -> RealmQuery<T>) : LiveData<RealmResults<T>>() {
private val listener = RealmChangeListener<RealmResults<T>> { results ->
value = results
}
private var realm: Realm? = null
private var results: RealmResults<T>? = null
override fun onActive() {
val realm = Realm.getInstance(realmConfiguration)
val results = query.invoke(realm).findAllAsync()
results.addChangeListener(listener)
this.realm = realm
this.results = results
}
override fun onInactive() {
results?.removeChangeListener(listener)
results = null
realm?.close()
realm = null
}
}

View File

@ -29,7 +29,8 @@ import im.vector.matrix.android.api.session.room.send.DraftService
import im.vector.matrix.android.api.session.room.send.SendService
import im.vector.matrix.android.api.session.room.state.StateService
import im.vector.matrix.android.api.session.room.timeline.TimelineService
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.api.util.toOptional
import im.vector.matrix.android.internal.database.mapper.RoomSummaryMapper
import im.vector.matrix.android.internal.database.model.RoomSummaryEntity
import im.vector.matrix.android.internal.database.model.RoomSummaryEntityFields
@ -56,19 +57,13 @@ internal class DefaultRoom @Inject constructor(override val roomId: String,
RelationService by relationService,
MembershipService by roomMembersService {
override fun getRoomSummaryLive(): LiveData<RoomSummary> {
val liveRealmData = RealmLiveData<RoomSummaryEntity>(monarchy.realmConfiguration) { realm ->
RoomSummaryEntity.where(realm, roomId).isNotEmpty(RoomSummaryEntityFields.DISPLAY_NAME)
}
return Transformations.map(liveRealmData) { results ->
val roomSummaries = results.map { roomSummaryMapper.map(it) }
if (roomSummaries.isEmpty()) {
// Create a dummy RoomSummary to avoid Crash during Sign Out or clear cache
RoomSummary(roomId)
} else {
roomSummaries.first()
}
override fun getRoomSummaryLive(): LiveData<Optional<RoomSummary>> {
val liveData = monarchy.findAllMappedWithChanges(
{ realm -> RoomSummaryEntity.where(realm, roomId).isNotEmpty(RoomSummaryEntityFields.DISPLAY_NAME) },
{ roomSummaryMapper.map(it) }
)
return Transformations.map(liveData) { results ->
results.firstOrNull().toOptional()
}
}

View File

@ -24,7 +24,6 @@ import com.zhuinden.monarchy.Monarchy
import im.vector.matrix.android.BuildConfig
import im.vector.matrix.android.api.session.room.send.DraftService
import im.vector.matrix.android.api.session.room.send.UserDraft
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.internal.database.mapper.DraftMapper
import im.vector.matrix.android.internal.database.model.DraftEntity
import im.vector.matrix.android.internal.database.model.RoomSummaryEntity
@ -51,12 +50,13 @@ internal class DefaultDraftService @AssistedInject constructor(@Assisted private
monarchy.writeAsync { realm ->
val roomSummaryEntity = RoomSummaryEntity.where(realm, roomId).findFirst() ?: realm.createObject(roomId)
val roomSummaryEntity = RoomSummaryEntity.where(realm, roomId).findFirst()
?: realm.createObject(roomId)
val userDraftsEntity = roomSummaryEntity.userDrafts
?: realm.createObject<UserDraftsEntity>().also {
roomSummaryEntity.userDrafts = it
}
?: realm.createObject<UserDraftsEntity>().also {
roomSummaryEntity.userDrafts = it
}
userDraftsEntity.let { userDraftEntity ->
// Save only valid draft
@ -150,16 +150,16 @@ internal class DefaultDraftService @AssistedInject constructor(@Assisted private
}
override fun getDraftsLive(): LiveData<List<UserDraft>> {
val liveData = RealmLiveData(monarchy.realmConfiguration) {
UserDraftsEntity.where(it, roomId)
}
return Transformations.map(liveData) { userDraftsEntities ->
userDraftsEntities.firstOrNull()?.let { userDraftEntity ->
userDraftEntity.userDrafts.map { draftEntity ->
DraftMapper.map(draftEntity)
val liveData = monarchy.findAllMappedWithChanges(
{ UserDraftsEntity.where(it, roomId) },
{
it.userDrafts.map { draft ->
DraftMapper.map(draft)
}
}
} ?: emptyList()
)
return Transformations.map(liveData) {
it.firstOrNull() ?: emptyList()
}
}
}

View File

@ -25,7 +25,7 @@ import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.session.room.model.ReadReceipt
import im.vector.matrix.android.api.session.room.read.ReadService
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.api.util.toOptional
import im.vector.matrix.android.internal.database.mapper.ReadReceiptsSummaryMapper
import im.vector.matrix.android.internal.database.model.ReadMarkerEntity
import im.vector.matrix.android.internal.database.model.ReadReceiptEntity
@ -82,33 +82,33 @@ internal class DefaultReadService @AssistedInject constructor(@Assisted private
}
override fun getReadMarkerLive(): LiveData<Optional<String>> {
val liveRealmData = RealmLiveData(monarchy.realmConfiguration) { realm ->
ReadMarkerEntity.where(realm, roomId)
}
return Transformations.map(liveRealmData) { results ->
Optional.from(results.firstOrNull()?.eventId)
val liveRealmData = monarchy.findAllMappedWithChanges(
{ ReadMarkerEntity.where(it, roomId) },
{ it.eventId }
)
return Transformations.map(liveRealmData) {
it.firstOrNull().toOptional()
}
}
override fun getMyReadReceiptLive(): LiveData<Optional<String>> {
val liveRealmData = RealmLiveData(monarchy.realmConfiguration) { realm ->
ReadReceiptEntity.where(realm, roomId = roomId, userId = userId)
}
return Transformations.map(liveRealmData) { results ->
Optional.from(results.firstOrNull()?.eventId)
val liveRealmData = monarchy.findAllMappedWithChanges(
{ ReadReceiptEntity.where(it, roomId = roomId, userId = userId) },
{ it.eventId }
)
return Transformations.map(liveRealmData) {
it.firstOrNull().toOptional()
}
}
override fun getEventReadReceiptsLive(eventId: String): LiveData<List<ReadReceipt>> {
val liveEntity = RealmLiveData(monarchy.realmConfiguration) { realm ->
ReadReceiptsSummaryEntity.where(realm, eventId)
}
return Transformations.map(liveEntity) { realmResults ->
realmResults.firstOrNull()?.let {
readReceiptsSummaryMapper.map(it)
}?.sortedByDescending {
it.originServerTs
} ?: emptyList()
val liveRealmData = monarchy.findAllMappedWithChanges(
{ ReadReceiptsSummaryEntity.where(it, eventId) },
{ readReceiptsSummaryMapper.map(it) }
)
return Transformations.map(liveRealmData) {
it.firstOrNull() ?: emptyList()
}
}
}

View File

@ -30,7 +30,8 @@ import im.vector.matrix.android.api.session.room.model.message.MessageType
import im.vector.matrix.android.api.session.room.model.relation.RelationService
import im.vector.matrix.android.api.session.room.timeline.TimelineEvent
import im.vector.matrix.android.api.util.Cancelable
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.api.util.toOptional
import im.vector.matrix.android.internal.database.helper.addSendingEvent
import im.vector.matrix.android.internal.database.mapper.asDomain
import im.vector.matrix.android.internal.database.model.EventAnnotationsSummaryEntity
@ -210,13 +211,13 @@ internal class DefaultRelationService @AssistedInject constructor(@Assisted priv
return TimelineSendEventWorkCommon.createWork<SendEventWorker>(sendWorkData, startChain)
}
override fun getEventSummaryLive(eventId: String): LiveData<EventAnnotationsSummary> {
val liveEntity = RealmLiveData(monarchy.realmConfiguration) { realm ->
EventAnnotationsSummaryEntity.where(realm, eventId)
}
return Transformations.map(liveEntity) { realmResults ->
realmResults.firstOrNull()?.asDomain()
?: EventAnnotationsSummary(eventId, emptyList(), null)
override fun getEventSummaryLive(eventId: String): LiveData<Optional<EventAnnotationsSummary>> {
val liveData = monarchy.findAllMappedWithChanges(
{ EventAnnotationsSummaryEntity.where(it, eventId)},
{ it.asDomain() }
)
return Transformations.map(liveData) { results ->
results.firstOrNull().toOptional()
}
}

View File

@ -26,7 +26,8 @@ import im.vector.matrix.android.api.session.room.timeline.Timeline
import im.vector.matrix.android.api.session.room.timeline.TimelineEvent
import im.vector.matrix.android.api.session.room.timeline.TimelineService
import im.vector.matrix.android.api.session.room.timeline.TimelineSettings
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.api.util.toOptional
import im.vector.matrix.android.internal.database.mapper.ReadReceiptsSummaryMapper
import im.vector.matrix.android.internal.database.mapper.TimelineEventMapper
import im.vector.matrix.android.internal.database.model.TimelineEventEntity
@ -73,12 +74,13 @@ internal class DefaultTimelineService @AssistedInject constructor(@Assisted priv
})
}
override fun getTimeLineEventLive(eventId: String): LiveData<TimelineEvent> {
val liveData = RealmLiveData(monarchy.realmConfiguration) {
TimelineEventEntity.where(it, roomId = roomId, eventId = eventId)
}
override fun getTimeLineEventLive(eventId: String): LiveData<Optional<TimelineEvent>> {
val liveData = monarchy.findAllMappedWithChanges(
{ TimelineEventEntity.where(it, roomId = roomId, eventId = eventId) },
{ timelineEventMapper.map(it) }
)
return Transformations.map(liveData) { events ->
events.firstOrNull()?.let { timelineEventMapper.map(it) }
events.firstOrNull().toOptional()
}
}

View File

@ -28,7 +28,6 @@ import im.vector.matrix.android.api.session.user.model.User
import im.vector.matrix.android.api.util.Cancelable
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.api.util.toOptional
import im.vector.matrix.android.internal.database.RealmLiveData
import im.vector.matrix.android.internal.database.mapper.asDomain
import im.vector.matrix.android.internal.database.model.UserEntity
import im.vector.matrix.android.internal.database.model.UserEntityFields
@ -63,20 +62,18 @@ internal class DefaultUserService @Inject constructor(private val monarchy: Mona
override fun getUser(userId: String): User? {
val userEntity = monarchy.fetchCopied { UserEntity.where(it, userId).findFirst() }
?: return null
?: return null
return userEntity.asDomain()
}
override fun liveUser(userId: String): LiveData<Optional<User>> {
val liveRealmData = RealmLiveData(monarchy.realmConfiguration) { realm ->
UserEntity.where(realm, userId)
}
return Transformations.map(liveRealmData) { results ->
results
.map { it.asDomain() }
.firstOrNull()
.toOptional()
val liveData = monarchy.findAllMappedWithChanges(
{ UserEntity.where(it, userId) },
{ it.asDomain() }
)
return Transformations.map(liveData) { results ->
results.firstOrNull().toOptional()
}
}

View File

@ -50,6 +50,7 @@ import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.android.internal.crypto.attachments.toElementToDecrypt
import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent
import im.vector.matrix.rx.rx
import im.vector.matrix.rx.unwrap
import im.vector.riotx.BuildConfig
import im.vector.riotx.R
import im.vector.riotx.core.extensions.postLiveEvent
@ -719,6 +720,7 @@ class RoomDetailViewModel @AssistedInject constructor(@Assisted initialState: Ro
private fun observeRoomSummary() {
room.rx().liveRoomSummary()
.unwrap()
.execute { async ->
copy(
asyncRoomSummary = async,

View File

@ -27,6 +27,7 @@ import im.vector.matrix.android.api.session.room.model.message.MessageType
import im.vector.matrix.android.api.session.room.timeline.TimelineEvent
import im.vector.matrix.android.api.session.room.timeline.getLastMessageContent
import im.vector.matrix.rx.RxRoom
import im.vector.matrix.rx.unwrap
import im.vector.riotx.core.extensions.canReact
import im.vector.riotx.core.platform.VectorViewModel
import im.vector.riotx.features.home.room.detail.timeline.format.NoticeEventFormatter
@ -51,7 +52,7 @@ data class MessageActionState(
fun senderName(): String = informationData.memberName?.toString() ?: ""
fun time(): String? = timelineEvent()?.root?.originServerTs?.let { dateFormat.format(Date(it)) }
?: ""
?: ""
fun canReact() = timelineEvent()?.canReact() == true
@ -61,7 +62,7 @@ data class MessageActionState(
val messageContent: MessageContent? = timelineEvent()?.getLastMessageContent()
if (messageContent is MessageTextContent && messageContent.format == MessageType.FORMAT_MATRIX_HTML) {
eventHtmlRenderer?.render(messageContent.formattedBody
?: messageContent.body)
?: messageContent.body)
} else {
messageContent?.body
}
@ -116,6 +117,7 @@ class MessageActionsViewModel @AssistedInject constructor(@Assisted
if (room == null) return
RxRoom(room)
.liveTimelineEvent(eventId)
.unwrap()
.execute {
copy(timelineEvent = it)
}

View File

@ -30,6 +30,7 @@ import im.vector.matrix.android.api.session.room.model.message.MessageType
import im.vector.matrix.android.api.session.room.send.SendState
import im.vector.matrix.android.api.session.room.timeline.TimelineEvent
import im.vector.matrix.android.api.session.room.timeline.hasBeenEdited
import im.vector.matrix.android.api.util.Optional
import im.vector.matrix.rx.RxRoom
import im.vector.riotx.R
import im.vector.riotx.core.extensions.canReact
@ -110,7 +111,9 @@ class MessageMenuViewModel @AssistedInject constructor(@Assisted initialState: M
}
}
private fun actionsForEvent(event: TimelineEvent): List<SimpleAction> {
private fun actionsForEvent(optionalEvent: Optional<TimelineEvent>): List<SimpleAction> {
val event = optionalEvent.getOrNull() ?: return emptyList()
val messageContent: MessageContent? = event.annotations?.editSummary?.aggregatedContent.toModel()
?: event.root.getClearContent().toModel()
val type = messageContent?.type

View File

@ -77,7 +77,7 @@ class QuickReactionViewModel @AssistedInject constructor(@Assisted initialState:
.liveAnnotationSummary(eventId)
.map { annotations ->
quickEmojis.map { emoji ->
ToggleState(emoji, annotations.reactionsSummary.firstOrNull { it.key == emoji }?.addedByMe
ToggleState(emoji, annotations.getOrNull()?.reactionsSummary?.firstOrNull { it.key == emoji }?.addedByMe
?: false)
}
}

View File

@ -27,6 +27,7 @@ import com.squareup.inject.assisted.AssistedInject
import im.vector.matrix.android.api.session.Session
import im.vector.matrix.android.api.session.room.model.ReactionAggregatedSummary
import im.vector.matrix.rx.RxRoom
import im.vector.matrix.rx.unwrap
import im.vector.riotx.core.platform.VectorViewModel
import im.vector.riotx.core.utils.isSingleEmoji
import im.vector.riotx.core.date.VectorDateFormatter
@ -87,6 +88,7 @@ class ViewReactionViewModel @AssistedInject constructor(@Assisted
private fun observeEventAnnotationSummaries() {
RxRoom(room)
.liveAnnotationSummary(eventId)
.unwrap()
.flatMapSingle { summaries ->
Observable
.fromIterable(summaries.reactionsSummary)