package com.gh.gamecenter.common.baselist;

import android.app.Application;

import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.annotation.NonNull;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Single;

/**
 * Created by khy on 21/03/18.
 */

public class NormalListViewModel<T> extends ListViewModel<T, T> {

    // TODO 作为构造函数从外部传入会引起内存泄漏，当 View 被销毁时，这个类的实例还会持有原有 View 的引用
    private OnDataObservable mDataObservable;

    public NormalListViewModel(@NonNull Application application, OnDataObservable dataObservable) {
        super(application);
        mDataObservable = dataObservable;
    }

    @Override
    protected void mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData, mResultLiveData::postValue);
    }


    @Deprecated
    @Override
    public Observable<List<T>> provideDataObservable(int offset) {
        return mDataObservable.provideDataObservable(offset);
    }

    @Override
    public Single<List<T>> provideDataSingle(int page) {
        return mDataObservable.provideDataSingle(page);
    }

    public static class Factory extends ViewModelProvider.NewInstanceFactory {
        @NonNull
        private final Application mApplication;

        private final OnDataObservable mDataObservable;

        public Factory(@NonNull Application application, OnDataObservable onDataObservable) {
            mApplication = application;
            mDataObservable = onDataObservable;
        }

        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            //noinspection unchecked
            return (T) new NormalListViewModel(mApplication, mDataObservable);
        }
    }
}
