[Android Docs] MVVM 구성 2편

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

MVVM Architecture & LiveData, ViewModel, LifeCycle Components

원본 문서

MVVM 구성 1편

📗 단어 정리 📘

OBS BUILD

영어한글
cumbersome번거로운, 다루기 힘든

In the example, News object is wrapped inside NewsViewModel and same is used for observing data inside fragment.

이 예제에서 뉴스 객체는 새뷰모델 내부에 래핑되어있고 프래그먼트 내부에 데이터를 옵저빙하기위해 사용됩니다.

Also, You should avoid keeping references of views in ViewModel,
that might lead memory leaks since ViewModel does not get destroyed on configuration changes.

또한 구성 변화에 파괴되지 않는 뷰모델때문에 메모리릭이 발생하는 뷰모델안에 뷰들의 레퍼런스들이 유지되는걸 피해야합니다.

However ViewModel won’t be retained on back press, if application is removed from recent or if system kills the activity.
In such cases onSaveInstance method has to be implemented to retain the needed data.

그러나 앱이 최근 제거되거나 시스템이 액티비티를 제거하는 경우 뷰모델은 백프레스에 포함되지 않습니다. 이런 경우 onSaveInstance를 사용해서 필요한 데이터를 유지할 수 있습니다.

Apart from this You can share data between two fragments using ViewModel.
It can be done something like this.

이 외에도 뷰모델을 사용하여 두 프래그먼트 사이에 데이터를 공유할 수 있습니다. 이런식으로 할 수 있습니다.

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}

public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.
        });
    }
}

Off course, You can do it using interfaces but that is a cumbersome way to handle communication.
If you use ViewModel, Activity and Fragment would not have any clue of communication.

물론 인터페이스를 사용할 수 있지만 그건 통신을 다루기에는 번거로운 방법입니다. 뷰모델을 사용한다면 액티비티와 프래그먼트는 어떠한 통신에 대한 단서가 없습니다.

They will be communicating through SharedViewModel. You can read more about it from here.

쉐어드뷰모델을 통해 통신할 수 있습니다.

Handling Life Cycle

This Architecture components comes with LifeCycle Observer.
As name suggests you can create an observer which will bind to a component’s lifecycle.

이 아키텍처 컴포넌트는 라이브사이클 옵저버와 함께 제공됩니다. 이름에서 추측할 수 있듯이 구성요소의 라이프사이클을 바인딩할 옵저버를 만들 수 있습니다.

In the below example SomeObserver is implementing LifecycleObserver class.
SomeObserver is bound to an activity so it will follow activity’s lifecycle.

아래 예제는 라이프사이클옵저버 클래스를 구현하고 있습니다. 옵저버는 액티비티에 바인딩 되어있으므로 액티비티 라이프사이클을 따릅니다.

As Activity’s onResume gets called, onResume of SomeObserver will also be called since it is linked to ON_RESUME event of Activity.

액티비티의 onResume이 호출되면 옵저버의 onResume 또한 액티비티 onResume이벤트에 연결되어있기 때문에 호출됩니다.

// registering observer in activity class
getLifecycle().addObserver(new SomeObserver());
// implementing LifecycleObserver class
public class SomeObserver implements LifecycleObserver {

    final String TAG = this.getClass().getSimpleName().toString();

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d(TAG, "onResume called");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.d(TAG, "onPause called");
    }
}

Use case: You want to fetch user’s fine location only if activity is visible. if not then coarse location.

사용사례: 액티비티가 보여지는 경우에만 유저의 정확한 위치를 찾기를 원할 때. 그렇지 않을 경우 대략적인 위치.

For this, In the observer class for onResume and onPause method you can switch the location update source from coarse to fine or vice-versa.

이런 경우 onResume와 onPause 메소드에 대한 옵저버 클래스에서 대략적에서 정확하게 혹은 반대로 위치를 업데이트하도록 전환할 수 있습니다.

Fragments and Activities already implement the LifeCycleOwner interface in Support Library 26.1.0 and later.

프래그먼트나 액티비티들은 이미 라이프사이클옵저버 인터페이스를 해당 버전과 이후에서 구현합니다.

Before that you would have to extend LifeCycleFragment or LifeCycleActivity for fragment and activity correspondingly.

그 전에 프래그먼트나 액티비티에 대해 라이프사이클 프래그먼트나 라이프사이클 액티비티를 상응하게 확장해야합니다.

Also, You can make your own class Lifecycle Owner by implementing LifeCycleOwner class and mark the methods which you want to expose using LifecycleRegistry.

또한 라이프사이클 소유를 구현함으로써 LifeCycleOwner 클래스를 만들고 LifecycleRegistry를 사용하여 노출하고자하는 메소드를 표시할 수 있습니다.

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

We are done with Architecture components. Let’s talk about MVVM Architecture now.

우리는 아키텍처 구성요소를 완료했습니다. MVVM 아키텍처에 대해 지금 말해보겠습니다.

profile
항상 배우려는 자세로

0개의 댓글