Created
June 20, 2018 16:34
-
-
Save photizzo/7f9f270d332239ea81446c9e5f6e6f36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rideon.user.activities; | |
import android.content.Context; | |
import android.os.Bundle; | |
import android.support.v7.widget.LinearLayoutManager; | |
import android.support.v7.widget.RecyclerView; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog; | |
import com.github.javiersantos.materialstyleddialogs.enums.Style; | |
import com.google.gson.Gson; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonParser; | |
import com.rideon.user.R; | |
import com.rideon.user.adapters.Availability; | |
import com.rideon.user.api.ApiService; | |
import com.rideon.user.api.ApiUtils; | |
import com.rideon.user.helpers.RideOnProgress; | |
import com.rideon.user.models.Driver; | |
import com.rideon.user.models.DriverCarProfile; | |
import com.rideon.user.models.DriverProfile; | |
import com.rideon.user.models.DriverResponse; | |
import com.rideon.user.util.ShakeListener; | |
import com.rideon.user.util.UtilsContainer; | |
import java.util.ArrayList; | |
import butterknife.BindView; | |
import butterknife.ButterKnife; | |
import io.reactivex.Observable; | |
import io.reactivex.ObservableSource; | |
import io.reactivex.android.schedulers.AndroidSchedulers; | |
import io.reactivex.disposables.CompositeDisposable; | |
import io.reactivex.functions.BiFunction; | |
import io.reactivex.functions.Function; | |
import io.reactivex.observables.ConnectableObservable; | |
import io.reactivex.observers.DisposableObserver; | |
import io.reactivex.schedulers.Schedulers; | |
public class DriversActivity extends BaseActivity { | |
private static final String TAG = DriversActivity.class.getSimpleName(); | |
/*@BindView(R.id.driver_list_layout) | |
WaveSwipeRefreshLayout mSwipeLayout;*/ | |
@BindView(R.id.drivers_list) | |
RecyclerView mRecyclerView; | |
@BindView(R.id.sad_face) | |
ImageView mSadFace; | |
@BindView(R.id.no_drivers) | |
TextView mNoDriversMessage; | |
// @BindView(R.id.driver_recycler_layout) | |
// RelativeLayout mLayout; | |
LinearLayoutManager mLayoutManager; | |
ApiService mApiService; | |
String userID = ""; | |
String userToken = ""; | |
RideOnProgress mProgress; | |
ShakeListener mShake; | |
Availability availability; | |
ArrayList<Driver> drivers; | |
ArrayList<DriverProfile> driverProfileArrayList = new ArrayList<>(); | |
Context mContext; | |
//todo Preserve user lat and long in sharedpreference | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_drivers); | |
ButterKnife.bind(this); | |
mApiService = ApiUtils.getApiService(); | |
availability = new Availability(getApplicationContext(), driverProfileArrayList); | |
availability.notifyDataSetChanged(); | |
mProgress = new RideOnProgress(this); | |
mLayoutManager = new LinearLayoutManager(this); | |
//mLayoutManager.setStackFromEnd(true); | |
//mLayoutManager.setReverseLayout(true); | |
mRecyclerView.setLayoutManager(mLayoutManager); | |
mRecyclerView.setAdapter(availability); | |
/*mSwipeLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() { | |
@Override | |
public void onRefresh() { | |
getDriversAvailabilityObservable(); | |
} | |
});*/ | |
// mRecyclerView.setNestedScrollingEnabled(false); | |
//mPrefs = getSharedPreferences(UtilsContainer.SHARED_PREF_NAME, Context.MODE_PRIVATE); | |
userID = UtilsContainer.getUserID(); | |
userToken = UtilsContainer.getUserToken(); | |
Log.e("DriversActivity", userID + "\n" + userToken); | |
//Toast.makeText(this, "\n"+ "Bearer "+userToken, Toast.LENGTH_LONG).show(); | |
//Toast.makeText(this, userID + "Bearer "+userToken, Toast.LENGTH_LONG).show(); | |
fetchDriversDetails(); | |
} | |
/** | |
* using rxjava to make multiple network calls | |
*/ | |
private CompositeDisposable disposable = new CompositeDisposable(); | |
public void fetchDriversDetails() { | |
mProgress.showDialog(); | |
//mSwipeLayout.setRefreshing(false); | |
//mLayout.setBackgroundColor(Color.parseColor("#c0deed")); | |
Log.e("TAG", "fetch drivers details called "); | |
ConnectableObservable<JsonObject> driversAvailabilitiesObservable = getDriversAvailabilityObservable().replay(); | |
/** | |
* Fetching all tickets first | |
* Observable emits List<Ticket> at once | |
* All the items will be added to RecyclerView | |
* */ | |
disposable.add( | |
driversAvailabilitiesObservable | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribeWith(new DisposableObserver<JsonObject>() { | |
@Override | |
public void onNext(JsonObject driversAvailability) { | |
// Refreshing list | |
// if (driversAvailability != null) { | |
// Log.e(TAG, "No Driver"); | |
// Toast.makeText(DriversActivity.this, "No Available Drivers", Toast.LENGTH_SHORT).show(); | |
// } else { | |
processDriversAvailabilities(driversAvailability); | |
// } | |
} | |
@Override | |
public void onError(Throwable e) { | |
showError(e); | |
} | |
@Override | |
public void onComplete() { | |
//mProgress.dismiss(); | |
Log.e("TAG", "drivers availability emissions are complete "); | |
} | |
})); | |
/** | |
* Fetching individual ticket price | |
* First FlatMap converts single List<Ticket> to multiple emissions | |
* Second FlatMap makes HTTP call on each Ticket emission | |
* */ | |
disposable.add( | |
driversAvailabilitiesObservable | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
/** | |
* Converting List<Ticket> emission to single Ticket emissions | |
* */ | |
.concatMap(new Function<JsonObject, ObservableSource<Driver>>() { | |
@Override | |
public ObservableSource<Driver> apply(JsonObject driversObject) throws Exception { | |
//parse out list of drivers | |
JsonObject driversData = driversObject.get("data").getAsJsonObject(); | |
DriverResponse driverResponse = new Gson().fromJson(driversData, DriverResponse.class); | |
return Observable.fromIterable(driverResponse.getDriverList()); | |
} | |
}) | |
/** | |
* Fetching price on each Ticket emission | |
* */ | |
.concatMap(new Function<Driver, ObservableSource<DriverProfile>>() { | |
@Override | |
public ObservableSource<DriverProfile> apply(Driver driver) throws Exception { | |
return getDCdetails(getDriverProfile(String.valueOf(driver.getDriverIdentifier())), | |
getDriverCarDetails(String.valueOf(driver.getDriverIdentifier()))); | |
} | |
}).subscribeWith(new DisposableObserver<DriverProfile>() { | |
@Override | |
public void onNext(DriverProfile driverProfile) { | |
Log.e("TAG", "driver profile " + driverProfile.toString()); | |
driverProfileArrayList.add(driverProfile); | |
} | |
@Override | |
public void onError(Throwable e) { | |
Log.e("TAG", "zipper error"); | |
showError(e); | |
} | |
@Override | |
public void onComplete() { | |
Log.e("TAG", "setting drivers to profile"); | |
if (drivers == null) { | |
mProgress.dismiss(); | |
mSadFace.setVisibility(View.VISIBLE); | |
mNoDriversMessage.setVisibility(View.VISIBLE); | |
mRecyclerView.setVisibility(View.GONE); | |
return; | |
} | |
for (int i = 0; i < drivers.size(); i++) { | |
driverProfileArrayList.get(i).setDriver(drivers.get(i)); | |
mSadFace.setVisibility(View.GONE); | |
mNoDriversMessage.setVisibility(View.GONE); | |
mRecyclerView.setVisibility(View.VISIBLE); | |
} | |
mProgress.dismiss(); | |
availability.setDriverProfileArrayListData(driverProfileArrayList, mContext); | |
} | |
})); | |
// Calling connect to start emission | |
driversAvailabilitiesObservable.connect(); | |
} | |
/** | |
* Making Retrofit call to fetch all tickets | |
*/ | |
private Observable<JsonObject> getDriversAvailabilityObservable() { | |
return mApiService.fetchDriversAvailabilities(UtilsContainer.getUserToken(), UtilsContainer.getOriginLat(), UtilsContainer.getOriginLng(), UtilsContainer.getPickupAddress(), UtilsContainer.getPickupState()) | |
.toObservable() | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()); | |
} | |
/** | |
* Making Retrofit call to get single ticket price | |
* get price HTTP call returns Price object, but | |
* map() operator is used to change the return type to Ticket | |
*/ | |
private Observable<JsonObject> getDriverProfile(final String id) { | |
return mApiService.fetchDriverProfile(UtilsContainer.getUserToken(), id) | |
.toObservable() | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()); | |
} | |
/** | |
* Making Retrofit call to get single ticket price | |
* get price HTTP call returns Price object, but | |
* map() operator is used to change the return type to Ticket | |
*/ | |
private Observable<JsonObject> getDriverCarDetails(final String id) { | |
return mApiService.fetchDriverCarDetails(UtilsContainer.getUserToken(), id) | |
.toObservable() | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()); | |
} | |
/** | |
* @param driverobservable | |
* @param carObservable | |
* @return | |
*/ | |
private Observable<DriverProfile> getDCdetails(Observable<JsonObject> driverobservable, Observable<JsonObject> carObservable) { | |
return Observable.zip(driverobservable.onErrorReturn(new Function<Throwable, JsonObject>() { | |
@Override | |
public JsonObject apply(Throwable throwable) throws Exception { | |
return getErrorJsonString(); | |
} | |
}), carObservable.onErrorReturn(new Function<Throwable, JsonObject>() { | |
@Override | |
public JsonObject apply(Throwable throwable) throws Exception { | |
return getErrorJsonString(); | |
} | |
}), new BiFunction<JsonObject, JsonObject, DriverProfile>() { | |
@Override | |
public DriverProfile apply(JsonObject driverProfile, JsonObject carProfile) throws Exception { | |
DriverProfile driverProfile1 = new Gson().fromJson(driverProfile.get("data").getAsJsonObject(), DriverProfile.class); | |
// handle cases when driver particular driver car profile does not exist | |
if (carProfile.get("code").getAsInt() != 401) { | |
DriverCarProfile driverCarProfile = new Gson().fromJson(carProfile.get("data").getAsJsonObject(), DriverCarProfile.class); | |
driverProfile1.setDriverCarProfile(driverCarProfile); | |
} | |
return driverProfile1; | |
} | |
}); | |
} | |
/** | |
* method to parse jsonString to JsonObject | |
* | |
* @return | |
*/ | |
public JsonObject getErrorJsonString() { | |
String jsonString = "{\"error\":\"Unsuccessful request.\",\"code\":401,\"data\":\"\",\"status\":\"failed\"}"; | |
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject(); | |
return jsonObject; | |
} | |
/** | |
* log errors from the observers | |
* | |
* @param e | |
*/ | |
private void showError(Throwable e) { | |
Log.e("TAG", "showError: " + e.getMessage()); | |
new MaterialStyledDialog.Builder(this) | |
.setTitle(getString(R.string.failure_notice)) | |
.setStyle(Style.HEADER_WITH_ICON) | |
.setIcon(R.drawable.ic_sentiment_dissatisfied) | |
.setDescription(e.getMessage()) | |
.setPositiveText(R.string.ok) | |
// .onPositive((dialog, which) -> { | |
// Intent successIntent = new Intent(getActivity(), MainActivity.class); | |
// startActivity(successIntent); | |
// }) | |
.show(); | |
mProgress.dismiss(); | |
} | |
/** | |
* method to process the drivers availability when it is fetched from the server | |
* | |
* @param response | |
*/ | |
public void processDriversAvailabilities(JsonObject response) { | |
Log.e(TAG, "process drivers availabilties"); | |
if (response == null) { | |
//todo handle error cases | |
return; | |
} | |
JsonObject driversObject = response; | |
JsonObject driversData = driversObject.get("data").getAsJsonObject(); | |
DriverResponse driverResponse = new Gson().fromJson(driversData, DriverResponse.class); | |
Log.e("TAG", "driver response converted " + driverResponse.getDriverList().toString()); | |
//availability.setDriversData(drivers); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
disposable.dispose(); | |
} | |
@Override | |
protected void onResume() { | |
super.onResume(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment