[Android Docs] MVVM 구성 1편

박주호·2022년 4월 24일
0
post-thumbnail

MVVM Architecture & LiveData, ViewModel, LifeCycle Components

원본 문서

📗 단어 정리 📘

OBS BUILD

영어한글
come up with찾아내다, 내놓다
brief짧은, 잠깐 동안의, 간단한
consolidate통합하다
in the middle of도중에

MVVM Architecture & LiveData, ViewModel, LifeCycle Components

MVC, MVP and MVVM are some of the Architecture patterns used by developers around the world. Which one to use,
depends upon the requirement and how comfortable is one with the architecture pattern.

MVC, MVP 그리고 MVVM은 전세계 개발자들이 사용하는 아키텍처 패턴의 일부입니다. 어느것을 사용하는지는 요구사항과 어떤게 편한지에 따라 결정됩니다.

However you should try to use one, it helps to keep the code segregated, modularised, readable, decoupled and easier to test.

그러나 그중 하나를 사용한다면 그 패턴은 코드를 세분과 모듈화 읽기 분리 그리고 쉽게 테스트 하는걸 도와줍니다.

Since the android development started Google never came up with their own architecture until recently.

안드로이드 개발을 시작하고 구글은 최근까지 자체 아키텍처를 내놓지 않았다

Google has introduced android architecture components which includes Life cycles, ViewModel, Room and LiveData.

구글은 라이프사이클, 뷰모델, 룸 그릭 라이브데이터를 포함하는 안드로이드 아키텍처 컴포넌트를 도입했습니다.

Why am I here

This Article will provide brief of MVVM Architecture, LiveData, ViewModel and Lifecycle components.

이 기사에선 mvvm 아키텍처, 라이브데이터, 뷰모델 그리고 라이프사이클 컴포넌트에 대해 간단하게 설명할겁니다.

Let’s get started

Before we start, I would recommend you to download a project from here.
This Application displays list of news in a Recycler view and on click of any news item, detailed news will be opened in a WebView.

시작전 프로젝트를 다운받기를 추천합니다. 이 어플리케이션은 뉴스 아이템을 클릭하고 리사이클러뷰에 있는 뉴스 리스트를 보여줍니다. 세부적으로 뉴스는 웹뷰에서 열립니다.

You can also refer screenshots from here. As we go through the article,
we will be using pieces of code from this project to understand architecture pattern and components.

스크린샷을 여기에서 알아볼 수 있다. 우리의 아티클을 통해 우리는 아키텍처 패턴과 컴포넌트를 이해하기위해서 우리 프로젝트로부터 일부 코드를 사용할 것입니다.

Downloaded, Good to Go 👍🏻

So Finally there is an architecture(MVVM) which follows the Single Responsibility Principle.
Each component does single and unique Job, which is why it is recommended to write as many component classes as many needed.
Before moving to MVVM Let’s understand Android components.

최종적으로 mvvm은 단일 책임 원칙을 따릅니다. 각 컴포넌트는 단일이고 유일한 작업을 수행하므로 필요한 수만큼 많은 컴포넌트 클래스를 작성하는것을 추천합니다. mvvm으로 이동하기 전에 안드로이드 컴포넌트를 알아보겠습니다.

We will start with LiveData

LiveData is an observable holder class. It is like any other observer which implements Observer class,
but LiveData is also linked with component (activity/Fragment/Service) life cycle.

라이브데이터는 관찰가능한 홀더 클래스입니다. 옵저버 클래스를 구현하는 다른 옵저버와 비슷하지만 라이브데이터는 컴포넌트 라이프 사이클에 연결되어 있습니다.

In case a component is destroyed, it will automatically stop observing the changes and
release unused allocated memory which would help in avoiding memory leaks.

컴포넌트가 파괴되는 경우 자동으로 옵저빙을 멈추고 메모리 누수를 방지하기위해 도움이되는 메모리 할당 사용을 해제합니다.

Using LiveData you consolidate your UI since observer would be triggering the UI changes if there is any change in data properties.
We can wrap around an object to LiveData and start listening for data changes.

라이브데이터는 옵저버가 데이터 속성이 변경되면 ui변화를 트리거하고 있기때문에 ui를 통합합니다. 우리는 객체를 라이브데이터에 래핑할 수 있고 데이터 변화를 수신할 수 있습니다.

// setting value
public LiveData<News> getNews(String source) {
    final MutableLiveData<News> data = new MutableLiveData<>();
    getNews(source).enqueue(new Callback<News>() {
        @Override
        public void onResponse(Call<News> call, Response<News> response) {
            data.setValue(response.body());
        }

        @Override
        public void onFailure(Call<News> call, Throwable t) {
            data.setValue(null);
        }
    });
    return data;
}
//listening for change in <Object>. // this would be in ui layer
getObservableProject().observe(this, new Observer<Object>() {
    @Override
    public void onChanged(@Nullable Object obj) {
       // handle changes
    }
});

In the Above Example News object is being fetched by an api call and is wrapped inside LiveData.
UI layer observes LiveData object changes.

위 예제에서 뉴스 객체는 api호출에 의해 패치되고 라이브데이터 안에 래핑됩니다. ui레이어는 라이브데이터 객체 변화를 관찰합니다.

So on change of object properties, UI would be changed automatically.
Also, it will save us the trouble of handling cases such as
what happens if user kills activity in the middle of API call since it will stop listening to the changes as soon as activity is destroyed.

따라서 객체 속성이 변경되면 ui는 자동으로 변경됩니다. 또한 액티비티가 파괴되자마자 변경에 대한 리스닝을 멈추기 때문에 api호출 도중에 사용자가 액티비티를 종료 경우와 같은 케이스들을 처리를 보호해줍니다.

ViewModel

If you use a ViewModel, you would not have to worry about saving the data on configuration changes.

뷰모델을 사용한다면 구성변화에 데이터 저장에 대한 저장을 걱정하지 않아도 됩니다.

In general, on configuration change activity is recreated and so does every other data retrieval.

일반적으로 액티비티 구성변화는 새로 생성되고 다른 모든 데이터 검색도 마찬가지입니다.

It can be an API call, db call or any other data related operation.
ViewModel saves us all this trouble and keep the data alive until component is killed.

api 호춢 db호출 다른 데이터 관련 연산일 수 있습니다. 뷰모델은 우리가 모든 이런 문제점과 데이터를 컴포넌트가 죽기전까지 유지하는걸 해결합니다.

Let’s say we have an activity which displays result based upon searched query.
Activity gets search query text from another component and then makes an API call to display results.

우리는 검색 쿼리 결과를 보여주는 액티비티가 있다고 가정합시다. 액티비티는 다른 컴포넌트로부터 검색 쿼리 텍스트를 가져오고 api를 호출하여 결과를 표시합니다.

In this case if user rotates device, there would be repetitive API call.
If a ViewModel is used for any such cases then data would be saved automatically.
ViewModel objects are automatically retained on configuration changes.

이 경우 사용자가 디바이스를 회전시킨다면 api호출이 반복됩니다. 만약 이런경우 뷰모델을 사용한다면 데이터는 자동으로 저장됩니다. 뷰모델 객체는 자동으로 구성요소 변경에 대해 유지됩니다.

ViewModel objects are attached to component life cycle and only gets away when the component is destroyed.
In case of Activity it would be in onDestroy() and in case of Fragment it would be in onDetach().

뷰모델객체는 컴포넌트 라이프사이클에 부착되고 오직 컴포넌트가 파괴될 때 사라집니다. 액티비티의 경우 onDestroy()와 프래그먼트의 경우 onDetach()가 있습니다.

// View model for News Object
public class NewsViewModel extends AndroidViewModel {
    private final LiveData<News> newsLiveData;

    public ObservableField<News> news = new ObservableField<>();

    public NewsViewModel(@NonNull Application application) {
        super(application);
        // a differnt source can be passed, here i am passing techcrunch
        newsLiveData = NewsRepository.getInstance().getNews("techcrunch");
    }

    public LiveData<News> getObservableProject() {
        return newsLiveData;
    }
}
// accessing NewsModel Object
final NewsViewModel viewModel = ViewModelProviders.of(this, factory)
        .get(NewsViewModel.class);
viewModel.getObservableProject().observe(this, new Observer<News>() {
    @Override
    public void onChanged(@Nullable News news) {
      // 
    }
});
profile
항상 배우려는 자세로

0개의 댓글