package com.gh.gamecenter.common.mvvm;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.annotation.Nullable;

import com.gh.gamecenter.common.retrofit.Response;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by khy on 31/01/18.
 */

public class NetworkBoundResource<DataType> {

    private final MediatorLiveData<Resource<DataType>> result = new MediatorLiveData<>();

    public NetworkBoundResource(Observable<DataType> observable) {
        fetchFromNetwork(observable);
    }

    private void fetchFromNetwork(Observable<DataType> observable) {
        result.postValue(Resource.loading());
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<DataType>() {
                    @Override
                    public void onResponse(DataType response) {
                        result.postValue(Resource.success(response));
                    }

                    @Override
                    public void onFailure(@Nullable HttpException e) {
                        result.postValue(Resource.error(e));
                    }
                });
    }

    public LiveData<Resource<DataType>> asLiveData() {
        return result;
    }
}
