MVP에서 모델 상태를 복원하는 방법은 무엇입니까?

저스트헬로월드

앱 설명

메시지(메시지 풀에서 가져옴)가 표시되고 사용자가 화면을 클릭할 때 변경되는 MVP가 있는 Android 앱을 처음으로 구현하려고 합니다. 모든 메시지가 표시되면 프로세스가 다시 시작됩니다(같은 메시지 순서에 따라). 요구 사항은 앱이 닫히거나 다시 열릴 때 동일한 메시지를 표시하는 것입니다. 따라서 MVP 모델에서 일부 저장/복원 상태 메커니즘을 구현해야 합니다.

다음은 앱의 기본 데모입니다.

여기에 이미지 설명 입력

MVP 디자인

이 앱에 대해 이 MVP를 다음과 같이 구현했습니다.

  1. The Model takes care of what it will be the next message (it implements the application state).
  2. The Presenter decides when to ask for the next message (to update the state), depending on the received events from the user (through the View).
  3. The View decides how to show the actual message and communicates events from the user (clicks on the screen) to the presenter. In addition, since the View is also the MainActivity, it takes care to instantiate the Presenter and Model implementations. Finally, it saves the Model state (as a Parcelable) with onSaveInstanceState (and also restores it).

Some Code

(Partial) View implementation:

class MainActivity : AppCompatActivity(), ViewMVC {

    private lateinit var presenter: Presenter
    private var model: Model? = CircularModel(LinkedList<State>(Arrays.asList(
            State("First"),
            State("Second"),
            State("Third")

    )))

    override fun onCreate(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {
            model = savedInstanceState.getParcelable("model")
        }

        presenter = PresenterImpl(this, model!!)
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        outState?.putParcelable("model", model!!)
        super.onSaveInstanceState(outState)
    }

(Partial) Model implementation:

@Parcelize
class CircularModel constructor(var states: @RawValue Deque<State>?) : Model, Parcelable {

    override fun getModelState(): State {
        return states!!.peekFirst()
    }

    override fun getModelNextState(): State {
        // Black magic happening here!
        return getModelState()
    }
}

The Problem / My question

Since Presenter and Model should be "Android agnostic", saving the app state (i.e., the Model object) is taken care by the View. However, this breaks the principle where the View doesn't know the Model. My question is: how to save the Model object, without the View knowing the actual implementation of it? What is the best way to deal with the Model state in this scenario?

An actual solution could be to write the code to serialize the Model in the Model itself and save it for each getNextState(), but this would mean use Android calls in the Model (and reduce its testability).

Ryujin

You should use a different persistence mechanism. The onSaveInstanceState() is really used for situations where the OS needs to restore UI state because of things like configuration / orientation changes. It's not a general purpose storage mechanism.

The model is the correct place to persist data and it is correct that you should try to keep the model as Android agnostic as possible. What you can do is define an interface that represents your persistence requirements:

interface SampleRepo{ 
   fun saveData(...)
   fun getData(...)
}

Then your preferred persistence mechanism (e.g. SharedPreferences, SQlite etc.) in a class implements that interface. This is where your Android specific stuff will be hidden.

class SharedPrefRepo : SampleRepo{
   override fun saveData(...)
   override fun getData(...)
}

이상적으로는 위의 인스턴스를 모델 클래스(예: Dagger)에 주입할 수 있도록 몇 가지 주입 메커니즘이 필요합니다. 더 많은 배관 코드가 필요하지만 느슨한 연결의 대가입니다. 당신이하고있는 것과 같은 더 간단한 앱의 경우이 모든 것이 과도합니다. 그러나 적절한 Android 앱 아키텍처와 느슨한 결합을 연구하려는 경우 올바르게 수행하는 방법을 탐구할 가치가 있습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

사용자가 모델을 변경한 후 모델 상태를 복원하는 방법은 무엇입니까?

복원 모델을 사용하여 ggplot에서 범례를 삭제하는 방법은 무엇입니까?

Laravel 모델 상속-부모 모델에서 함수를 호출하는 방법은 무엇입니까?

Laravel 6에서 단위 테스트할 때 모델 관계 상태/상태를 처리하는 가장 좋은 방법은 무엇입니까?

텐서 보드를 복잡하게 만들지 않고 텐서 플로우에서 모델을 복원하는 방법은 무엇입니까?

tensorflow의 RNN 모델에서 셀 상태와 숨겨진 상태를 추출하는 방법은 무엇입니까?

모델에서 SelectList를 하드코딩하는 방법은 무엇입니까?

MVC / MVP 프레임 워크에서 단일 모델 / 컨트롤러와 연관되지 않은 페이지를 처리하는 방법은 무엇입니까?

Simulink에서 비선형 상태 공간 모델을 플로팅하는 방법은 무엇입니까?

회전 상태에서 동적 모델 이름을 확인하는 방법은 무엇입니까?

Laravel에서 모델 관계를 표시하는 방법은 무엇입니까?

Mongoose 모델에서 기호를 사용하는 방법은 무엇입니까?

뷰 모델에서 DelegateCommand를 사용하는 방법은 무엇입니까?

Django 모델에서 관계를 정의하는 방법은 무엇입니까?

모델에서 데이터를 설정하는 방법은 무엇입니까?

부모 모델 내에서 모델의 유효성 검사를 생략하는 방법은 무엇입니까?

Django에서 추상 모델을 만드는 방법은 무엇입니까?

TensorFlow Eager 모드 : 검사 점에서 모델을 복원하는 방법은 무엇입니까?

원시 객체에서 Eloquent 모델 인스턴스를 생성하는 방법은 무엇입니까?

쿼리를 사용하여 다른 모델에서 모델을 반환하는 방법은 무엇입니까?

zk에서 짝수 인덱스를 통해 모델을 반복하는 방법은 무엇입니까?

Haskell에서이 반복 구조를 모델링하는 방법은 무엇입니까?

R의`lm` 유형 모델에서`fitted` 객체를 반복하는 방법은 무엇입니까?

PySpark Word2vec 모델에서 반복 횟수를 설정하는 방법은 무엇입니까?

Django에서 모델 인스턴스를 복제하는 방법은 무엇입니까?

django에서 한 모델의 3가지 형태를 저장하는 방법은 무엇입니까?

파이썬에서 .pb 파일에서 Tensorflow 모델을 복원하는 방법은 무엇입니까?

Realm에서 3 가지 모델 간의 관계를 모델링하는 방법은 무엇입니까?

다른 뷰 모델에서 메인 뷰 모델의 함수를 호출하는 방법은 무엇입니까?

TOP 리스트

  1. 1

    JSoup javax.net.ssl.SSLHandshakeException : <url>과 일치하는 주체 대체 DNS 이름이 없습니다.

  2. 2

    상황에 맞는 메뉴 색상

  3. 3

    java.lang.UnsatisfiedLinkError : 지정된 모듈을 찾을 수 없습니다

  4. 4

    SMTPException : 전송 연결에서 데이터를 읽을 수 없음 : net_io_connectionclosed

  5. 5

    std :: regex의 일관성없는 동작

  6. 6

    Ionic 2 로더가 적시에 표시되지 않음

  7. 7

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  8. 8

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  9. 9

    Xcode10 유효성 검사 : 이미지에 투명성이 없지만 여전히 수락되지 않습니까?

  10. 10

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  11. 11

    SQL Server-현명한 데이터 문제 받기

  12. 12

    Windows cmd를 통해 Anaconda 환경에서 Python 스크립트 실행

  13. 13

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  14. 14

    내 페이지 번호의 서식을 어떻게 지정합니까?

  15. 15

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  16. 16

    Quickly 프로그램과 함께 작동하도록 Eclipse를 어떻게 설정할 수 있습니까?

  17. 17

    인코더없이 Azure 미디어 서비스 비디오 트림

  18. 18

    WSL 및 Ubuntu, 초기화 파일 이동 방법

  19. 19

    OpenCV에서. C ++ 컴파일러는 간단한 테스트 프로그램을 컴파일 할 수 없습니다. Clang ++ 사용

  20. 20

    마우스 휠 JQuery 이벤트 핸들러에 대한 방향 가져 오기

  21. 21

    ViewModel에서 UI 요소를 비동 시적으로 업데이트하는 방법

뜨겁다태그

보관