Use observeEvent when appropriate

This commit is contained in:
Benoit Marty 2019-06-12 13:19:52 +02:00
parent b47ef9220e
commit 9c654ba72c
6 changed files with 159 additions and 170 deletions

View File

@ -25,6 +25,7 @@ import androidx.lifecycle.ViewModelProviders
import im.vector.fragments.keysbackup.restore.KeysBackupRestoreFromPassphraseFragment
import im.vector.fragments.keysbackup.restore.KeysBackupRestoreSharedViewModel
import im.vector.riotredesign.R
import im.vector.riotredesign.core.extensions.observeEvent
import im.vector.riotredesign.core.platform.SimpleFragmentActivity

class KeysBackupRestoreActivity : SimpleFragmentActivity() {
@ -61,53 +62,48 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() {
}
})

viewModel.keyVersionResultError.observe(this, Observer { uxStateEvent ->
uxStateEvent?.getContentIfNotHandled()?.let {
AlertDialog.Builder(this)
.setTitle(R.string.unknown_error)
.setMessage(it)
.setCancelable(false)
.setPositiveButton(R.string.ok) { _, _ ->
//nop
finish()
}
.show()
}
})
viewModel.keyVersionResultError.observeEvent(this) { message ->
AlertDialog.Builder(this)
.setTitle(R.string.unknown_error)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok) { _, _ ->
//nop
finish()
}
.show()
}

if (viewModel.keyVersionResult.value == null) {
//We need to fetch from API
viewModel.getLatestVersion(this)
}

viewModel.navigateEvent.observe(this, Observer { uxStateEvent ->
when (uxStateEvent?.getContentIfNotHandled()) {
viewModel.navigateEvent.observeEvent(this) { uxStateEvent ->
when (uxStateEvent) {
KeysBackupRestoreSharedViewModel.NAVIGATE_TO_RECOVER_WITH_KEY -> {
supportFragmentManager.beginTransaction()
.replace(R.id.container, KeysBackupRestoreFromKeyFragment.newInstance())
.addToBackStack(null)
.commit()
}
KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> {
KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> {
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
supportFragmentManager.beginTransaction()
.replace(R.id.container, KeysBackupRestoreSuccessFragment.newInstance())
.commit()
}
}
})
}

viewModel.loadingEvent.observe(this, Observer {
updateWaitingView(it)
})

viewModel.importRoomKeysFinishWithResult.observe(this, Observer {
it?.getContentIfNotHandled()?.let {
//set data?
setResult(Activity.RESULT_OK)
finish()
}
})
viewModel.importRoomKeysFinishWithResult.observeEvent(this) {
//set data?
setResult(Activity.RESULT_OK)
finish()
}
}

}

View File

@ -25,6 +25,7 @@ import androidx.lifecycle.ViewModelProviders
import im.vector.fragments.keysbackup.setup.KeysBackupSetupSharedViewModel
import im.vector.riotredesign.R
import im.vector.riotredesign.core.dialogs.ExportKeysDialog
import im.vector.riotredesign.core.extensions.observeEvent
import im.vector.riotredesign.core.platform.SimpleFragmentActivity

class KeysBackupSetupActivity : SimpleFragmentActivity() {
@ -61,21 +62,21 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
}
})

viewModel.navigateEvent.observe(this, Observer { uxStateEvent ->
when (uxStateEvent?.getContentIfNotHandled()) {
KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_2 -> {
viewModel.navigateEvent.observeEvent(this) { uxStateEvent ->
when (uxStateEvent) {
KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_2 -> {
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
supportFragmentManager.beginTransaction()
.replace(R.id.container, KeysBackupSetupStep2Fragment.newInstance())
.commit()
}
KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_3 -> {
KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_3 -> {
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
supportFragmentManager.beginTransaction()
.replace(R.id.container, KeysBackupSetupStep3Fragment.newInstance())
.commit()
}
KeysBackupSetupSharedViewModel.NAVIGATE_FINISH -> {
KeysBackupSetupSharedViewModel.NAVIGATE_FINISH -> {
val resultIntent = Intent()
viewModel.keysVersion.value?.version?.let {
resultIntent.putExtra(KEYS_VERSION, it)
@ -87,7 +88,7 @@ class KeysBackupSetupActivity : SimpleFragmentActivity() {
exportKeysManually()
}
}
})
}


viewModel.prepareRecoverFailError.observe(this, Observer { error ->

View File

@ -22,11 +22,12 @@ import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import im.vector.matrix.android.api.session.crypto.sas.CancelCode
import im.vector.matrix.android.api.session.crypto.sas.IncomingSasVerificationTransaction
import im.vector.matrix.android.api.session.crypto.sas.OutgoingSasVerificationRequest
import im.vector.matrix.android.api.session.crypto.sas.CancelCode
import im.vector.matrix.android.api.session.crypto.sas.SasVerificationTxState
import im.vector.riotredesign.R
import im.vector.riotredesign.core.extensions.observeEvent
import im.vector.riotredesign.core.platform.SimpleFragmentActivity
import im.vector.riotredesign.core.platform.WaitingViewData

@ -108,20 +109,20 @@ class SASVerificationActivity : SimpleFragmentActivity() {
.commitNow()
}
IncomingSasVerificationTransaction.UxState.WAIT_FOR_VERIFICATION,
IncomingSasVerificationTransaction.UxState.SHOW_SAS -> {
IncomingSasVerificationTransaction.UxState.SHOW_SAS -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.no_anim, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationShortCodeFragment.newInstance())
.commitNow()
}
IncomingSasVerificationTransaction.UxState.VERIFIED -> {
IncomingSasVerificationTransaction.UxState.VERIFIED -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.no_anim, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationVerifiedFragment.newInstance())
.commitNow()
}
IncomingSasVerificationTransaction.UxState.CANCELLED_BY_ME,
IncomingSasVerificationTransaction.UxState.CANCELLED_BY_OTHER -> {
IncomingSasVerificationTransaction.UxState.CANCELLED_BY_OTHER -> {
viewModel.navigateCancel()
}
}
@ -139,29 +140,29 @@ class SASVerificationActivity : SimpleFragmentActivity() {
.commitNow()
}
OutgoingSasVerificationRequest.UxState.SHOW_SAS,
OutgoingSasVerificationRequest.UxState.WAIT_FOR_VERIFICATION -> {
OutgoingSasVerificationRequest.UxState.WAIT_FOR_VERIFICATION -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.no_anim, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationShortCodeFragment.newInstance())
.commitNow()
}
OutgoingSasVerificationRequest.UxState.VERIFIED -> {
OutgoingSasVerificationRequest.UxState.VERIFIED -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.no_anim, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationVerifiedFragment.newInstance())
.commitNow()
}
OutgoingSasVerificationRequest.UxState.CANCELLED_BY_ME,
OutgoingSasVerificationRequest.UxState.CANCELLED_BY_OTHER -> {
OutgoingSasVerificationRequest.UxState.CANCELLED_BY_OTHER -> {
viewModel.navigateCancel()
}
}
}
}

viewModel.navigateEvent.observe(this, Observer { uxStateEvent ->
when (uxStateEvent?.getContentIfNotHandled()) {
SasVerificationViewModel.NAVIGATE_FINISH -> {
viewModel.navigateEvent.observeEvent(this) { uxStateEvent ->
when (uxStateEvent) {
SasVerificationViewModel.NAVIGATE_FINISH -> {
finish()
}
SasVerificationViewModel.NAVIGATE_FINISH_SUCCESS -> {
@ -171,33 +172,33 @@ class SASVerificationActivity : SimpleFragmentActivity() {
setResult(Activity.RESULT_OK, dataResult)
finish()
}
SasVerificationViewModel.NAVIGATE_SAS_DISPLAY -> {
SasVerificationViewModel.NAVIGATE_SAS_DISPLAY -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationShortCodeFragment.newInstance())
.commitNow()
}
SasVerificationViewModel.NAVIGATE_SUCCESS -> {
SasVerificationViewModel.NAVIGATE_SUCCESS -> {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_fade_out)
.replace(R.id.container, SASVerificationVerifiedFragment.newInstance())
.commitNow()
}
SasVerificationViewModel.NAVIGATE_CANCELLED -> {
SasVerificationViewModel.NAVIGATE_CANCELLED -> {
val isCancelledByMe = viewModel.transaction?.state == SasVerificationTxState.Cancelled
val humanReadableReason = when (viewModel.transaction?.cancelledReason) {
CancelCode.User -> getString(R.string.sas_error_m_user)
CancelCode.Timeout -> getString(R.string.sas_error_m_timeout)
CancelCode.UnknownTransaction -> getString(R.string.sas_error_m_unknown_transaction)
CancelCode.UnknownMethod -> getString(R.string.sas_error_m_unknown_method)
CancelCode.User -> getString(R.string.sas_error_m_user)
CancelCode.Timeout -> getString(R.string.sas_error_m_timeout)
CancelCode.UnknownTransaction -> getString(R.string.sas_error_m_unknown_transaction)
CancelCode.UnknownMethod -> getString(R.string.sas_error_m_unknown_method)
CancelCode.MismatchedCommitment -> getString(R.string.sas_error_m_mismatched_commitment)
CancelCode.MismatchedSas -> getString(R.string.sas_error_m_mismatched_sas)
CancelCode.UnexpectedMessage -> getString(R.string.sas_error_m_unexpected_message)
CancelCode.InvalidMessage -> getString(R.string.sas_error_m_invalid_message)
CancelCode.MismatchedKeys -> getString(R.string.sas_error_m_key_mismatch)
CancelCode.MismatchedSas -> getString(R.string.sas_error_m_mismatched_sas)
CancelCode.UnexpectedMessage -> getString(R.string.sas_error_m_unexpected_message)
CancelCode.InvalidMessage -> getString(R.string.sas_error_m_invalid_message)
CancelCode.MismatchedKeys -> getString(R.string.sas_error_m_key_mismatch)
// Use user error
CancelCode.UserMismatchError -> getString(R.string.sas_error_m_user_error)
null -> getString(R.string.sas_error_unknown)
CancelCode.UserMismatchError -> getString(R.string.sas_error_m_user_error)
null -> getString(R.string.sas_error_unknown)
}
val message =
if (isCancelledByMe) getString(R.string.sas_cancelled_by_me, humanReadableReason)
@ -216,7 +217,7 @@ class SASVerificationActivity : SimpleFragmentActivity() {
}
}
}
})
}

viewModel.loadingLiveEvent.observe(this, Observer {
if (it == null) {

View File

@ -36,7 +36,6 @@ import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
@ -192,15 +191,13 @@ class RoomDetailFragment :
textComposerViewModel.subscribe { renderTextComposerState(it) }
roomDetailViewModel.sendMessageResultLiveData.observeEvent(this) { renderSendMessageResult(it) }

roomDetailViewModel.nonBlockingPopAlert.observe(this, Observer { liveEvent ->
liveEvent.getContentIfNotHandled()?.let {
val message = requireContext().getString(it.first, *it.second.toTypedArray())
showSnackWithMessage(message, Snackbar.LENGTH_LONG)
}
})
actionViewModel.actionCommandEvent.observe(this, Observer {
roomDetailViewModel.nonBlockingPopAlert.observeEvent(this) { pair ->
val message = requireContext().getString(pair.first, *pair.second.toTypedArray())
showSnackWithMessage(message, Snackbar.LENGTH_LONG)
}
actionViewModel.actionCommandEvent.observeEvent(this) {
handleActions(it)
})
}

roomDetailViewModel.selectSubscribe(
RoomDetailViewState::sendMode,
@ -614,101 +611,98 @@ class RoomDetailFragment :
textComposerViewModel.process(TextComposerActions.QueryUsers(query))
}

private fun handleActions(it: LiveEvent<ActionsHandler.ActionData>?) {
it?.getContentIfNotHandled()?.let { actionData ->

when (actionData.actionId) {
MessageMenuViewModel.ACTION_ADD_REACTION -> {
val eventId = actionData.data?.toString() ?: return
startActivityForResult(EmojiReactionPickerActivity.intent(requireContext(), eventId), REACTION_SELECT_REQUEST_CODE)
}
MessageMenuViewModel.ACTION_VIEW_REACTIONS -> {
val messageInformationData = actionData.data as? MessageInformationData
?: return
ViewReactionBottomSheet.newInstance(roomDetailArgs.roomId, messageInformationData)
.show(requireActivity().supportFragmentManager, "DISPLAY_REACTIONS")
}
MessageMenuViewModel.ACTION_COPY -> {
//I need info about the current selected message :/
copyToClipboard(requireContext(), actionData.data?.toString() ?: "", false)
val msg = requireContext().getString(R.string.copied_to_clipboard)
showSnackWithMessage(msg, Snackbar.LENGTH_SHORT)
}
MessageMenuViewModel.ACTION_DELETE -> {
val eventId = actionData.data?.toString() ?: return
roomDetailViewModel.process(RoomDetailActions.RedactAction(eventId, context?.getString(R.string.event_redacted_by_user_reason)))
}
MessageMenuViewModel.ACTION_SHARE -> {
//TODO current data communication is too limited
//Need to now the media type
actionData.data?.toString()?.let {
//TODO bad, just POC
BigImageViewer.imageLoader().loadImage(
actionData.hashCode(),
Uri.parse(it),
object : ImageLoader.Callback {
override fun onFinish() {}

override fun onSuccess(image: File?) {
if (image != null)
shareMedia(requireContext(), image, "image/*")
}

override fun onFail(error: Exception?) {}

override fun onCacheHit(imageType: Int, image: File?) {}

override fun onCacheMiss(imageType: Int, image: File?) {}

override fun onProgress(progress: Int) {}

override fun onStart() {}
private fun handleActions(actionData: ActionsHandler.ActionData) {
when (actionData.actionId) {
MessageMenuViewModel.ACTION_ADD_REACTION -> {
val eventId = actionData.data?.toString() ?: return
startActivityForResult(EmojiReactionPickerActivity.intent(requireContext(), eventId), REACTION_SELECT_REQUEST_CODE)
}
MessageMenuViewModel.ACTION_VIEW_REACTIONS -> {
val messageInformationData = actionData.data as? MessageInformationData
?: return
ViewReactionBottomSheet.newInstance(roomDetailArgs.roomId, messageInformationData)
.show(requireActivity().supportFragmentManager, "DISPLAY_REACTIONS")
}
MessageMenuViewModel.ACTION_COPY -> {
//I need info about the current selected message :/
copyToClipboard(requireContext(), actionData.data?.toString() ?: "", false)
val msg = requireContext().getString(R.string.copied_to_clipboard)
showSnackWithMessage(msg, Snackbar.LENGTH_SHORT)
}
MessageMenuViewModel.ACTION_DELETE -> {
val eventId = actionData.data?.toString() ?: return
roomDetailViewModel.process(RoomDetailActions.RedactAction(eventId, context?.getString(R.string.event_redacted_by_user_reason)))
}
MessageMenuViewModel.ACTION_SHARE -> {
//TODO current data communication is too limited
//Need to now the media type
actionData.data?.toString()?.let {
//TODO bad, just POC
BigImageViewer.imageLoader().loadImage(
actionData.hashCode(),
Uri.parse(it),
object : ImageLoader.Callback {
override fun onFinish() {}

override fun onSuccess(image: File?) {
if (image != null)
shareMedia(requireContext(), image, "image/*")
}

)
}
}
MessageMenuViewModel.VIEW_SOURCE,
MessageMenuViewModel.VIEW_DECRYPTED_SOURCE -> {
val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_event_content, null)
view.findViewById<TextView>(R.id.event_content_text_view)?.let {
it.text = actionData.data?.toString() ?: ""
}
override fun onFail(error: Exception?) {}

AlertDialog.Builder(requireActivity())
.setView(view)
.setPositiveButton(R.string.ok) { dialog, id -> dialog.cancel() }
.show()
}
MessageMenuViewModel.ACTION_QUICK_REACT -> {
//eventId,ClickedOn,Opposite
(actionData.data as? Triple<String, String, String>)?.let { (eventId, clickedOn, opposite) ->
roomDetailViewModel.process(RoomDetailActions.UpdateQuickReactAction(eventId, clickedOn, opposite))
}
}
MessageMenuViewModel.ACTION_EDIT -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterEditMode(eventId))
}
MessageMenuViewModel.ACTION_QUOTE -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterQuoteMode(eventId))
}
MessageMenuViewModel.ACTION_REPLY -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterReplyMode(eventId))
}
MessageMenuViewModel.ACTION_COPY_PERMALINK -> {
val eventId = actionData.data.toString()
val permalink = PermalinkFactory.createPermalink(roomDetailArgs.roomId, eventId)
copyToClipboard(requireContext(), permalink, false)
showSnackWithMessage(requireContext().getString(R.string.copied_to_clipboard), Snackbar.LENGTH_SHORT)
override fun onCacheHit(imageType: Int, image: File?) {}

override fun onCacheMiss(imageType: Int, image: File?) {}

override fun onProgress(progress: Int) {}

override fun onStart() {}

}

)
}
else -> {
Toast.makeText(context, "Action ${actionData.actionId} not implemented", Toast.LENGTH_LONG).show()
}
MessageMenuViewModel.VIEW_SOURCE,
MessageMenuViewModel.VIEW_DECRYPTED_SOURCE -> {
val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_event_content, null)
view.findViewById<TextView>(R.id.event_content_text_view)?.let {
it.text = actionData.data?.toString() ?: ""
}

AlertDialog.Builder(requireActivity())
.setView(view)
.setPositiveButton(R.string.ok) { dialog, id -> dialog.cancel() }
.show()
}
MessageMenuViewModel.ACTION_QUICK_REACT -> {
//eventId,ClickedOn,Opposite
(actionData.data as? Triple<String, String, String>)?.let { (eventId, clickedOn, opposite) ->
roomDetailViewModel.process(RoomDetailActions.UpdateQuickReactAction(eventId, clickedOn, opposite))
}
}
MessageMenuViewModel.ACTION_EDIT -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterEditMode(eventId))
}
MessageMenuViewModel.ACTION_QUOTE -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterQuoteMode(eventId))
}
MessageMenuViewModel.ACTION_REPLY -> {
val eventId = actionData.data.toString()
roomDetailViewModel.process(RoomDetailActions.EnterReplyMode(eventId))
}
MessageMenuViewModel.ACTION_COPY_PERMALINK -> {
val eventId = actionData.data.toString()
val permalink = PermalinkFactory.createPermalink(roomDetailArgs.roomId, eventId)
copyToClipboard(requireContext(), permalink, false)
showSnackWithMessage(requireContext().getString(R.string.copied_to_clipboard), Snackbar.LENGTH_SHORT)

}
else -> {
Toast.makeText(context, "Action ${actionData.actionId} not implemented", Toast.LENGTH_LONG).show()
}
}
}

View File

@ -30,6 +30,7 @@ import androidx.lifecycle.ViewModelProviders
import com.google.android.material.tabs.TabLayout
import im.vector.riotredesign.EmojiCompatFontProvider
import im.vector.riotredesign.R
import im.vector.riotredesign.core.extensions.observeEvent
import im.vector.riotredesign.core.platform.VectorBaseActivity
import kotlinx.android.synthetic.main.activity_emoji_reaction_picker.*
import org.koin.android.ext.android.inject
@ -102,18 +103,16 @@ class EmojiReactionPickerActivity : VectorBaseActivity(), EmojiCompatFontProvide
}
})

viewModel.navigateEvent.observe(this, Observer {
it.getContentIfNotHandled()?.let {
if (it == EmojiChooserViewModel.NAVIGATE_FINISH) {
//finish with result
val dataResult = Intent()
dataResult.putExtra(EXTRA_REACTION_RESULT, viewModel.selectedReaction)
dataResult.putExtra(EXTRA_EVENT_ID, viewModel.eventId)
setResult(Activity.RESULT_OK, dataResult)
finish()
}
viewModel.navigateEvent.observeEvent(this) {
if (it == EmojiChooserViewModel.NAVIGATE_FINISH) {
//finish with result
val dataResult = Intent()
dataResult.putExtra(EXTRA_REACTION_RESULT, viewModel.selectedReaction)
dataResult.putExtra(EXTRA_EVENT_ID, viewModel.eventId)
setResult(Activity.RESULT_OK, dataResult)
finish()
}
})
}
}

override fun compatibilityFontUpdate(typeface: Typeface?) {

View File

@ -19,7 +19,6 @@ package im.vector.riotredesign.features.roomdirectory
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.airbnb.epoxy.EpoxyVisibilityTracker
@ -30,6 +29,7 @@ import com.jakewharton.rxbinding2.widget.RxTextView
import im.vector.matrix.android.api.session.room.model.roomdirectory.PublicRoom
import im.vector.riotredesign.R
import im.vector.riotredesign.core.error.ErrorFormatter
import im.vector.riotredesign.core.extensions.observeEvent
import im.vector.riotredesign.core.platform.VectorBaseFragment
import im.vector.riotredesign.features.themes.ThemeUtils
import io.reactivex.rxkotlin.subscribeBy
@ -79,12 +79,10 @@ class PublicRoomsFragment : VectorBaseFragment(), PublicRoomsController.Callback
navigationViewModel.goTo(RoomDirectoryActivity.Navigation.CreateRoom)
}

viewModel.joinRoomErrorLiveData.observe(this, Observer {
it.getContentIfNotHandled()?.let { throwable ->
Snackbar.make(publicRoomsCoordinator, errorFormatter.toHumanReadable(throwable), Snackbar.LENGTH_SHORT)
.show()
}
})
viewModel.joinRoomErrorLiveData.observeEvent(this) { throwable ->
Snackbar.make(publicRoomsCoordinator, errorFormatter.toHumanReadable(throwable), Snackbar.LENGTH_SHORT)
.show()
}
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {