Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. My scenario: a controller retrieves channels (/asset/data/media same same) two different components would like to receive the response.
  2. problem: I don't want to run the BE request twice, and I don't want the components "know" that the controller is using rxJava.
  3.  
  4. Controller:
  5. ct'r
  6. public TvGuideChannelsController(String channelId) {
  7. ....
  8. createChannelObservable();
  9. }
  10.  
  11. I created ConnectableObservable so I can replay the result without another server request.
  12. the connect is needed only once.
  13.  
  14. protected void createChannelObservable() {
  15.  
  16. channelsObservable = Observable.create(new ObservableOnSubscribe<List<AssetInfo>>() {
  17. @Override
  18. public void subscribe(@NonNull final ObservableEmitter<List<AssetInfo>> e) throws Exception {
  19.  
  20. TvpapiApi.getInstance().requestChannelMediaListUsingGetChannelMultiFilter(mChannelID, 250, APIConstants.MediaOrderByEnum.ABC, 0, new OnTvinciAPIResponse<List<AssetInfo>>() {
  21.  
  22. @Override
  23. public void onData(TvpapiApi.APIResponse<List<AssetInfo>> data) {
  24. mChannels = data.getResponse();
  25. EpgManager.getInstance().setMediaChannels(data.getResponse());
  26. e.onNext(data.getResponse());
  27. }
  28.  
  29. @Override
  30. public void onError(TvpapiApi.APIErrorTypes type) {
  31. e.onError(new Throwable(type.getExtraReason()));
  32. }
  33. });
  34. }
  35. }).replay();
  36.  
  37. channelsObservable.connect();
  38. }
  39.  
  40. when a component want to use the response it requestChannels with TvGuideResponse interface (not consumer) so the component will not know how the controller's implementation.
  41.  
  42. @Override
  43. public void requestChannels(final TvGuideResponse response) {
  44.  
  45. subscribeOnChannels(new Consumer<List<AssetInfo>>() {
  46. @Override
  47. public void accept(List<AssetInfo> assets) {
  48. response.onChannels(assets);
  49. }
  50. });
  51. }
  52.  
  53. the contoller creates a new constumer for each component request and the observable will replay the response for each one.
  54.  
  55. private void subscribeOnChannels(final Consumer<List<AssetInfo>> assetsConsumer) {
  56. if (channelsObservable != null){
  57. channelsObservable.subscribe(new io.reactivex.functions.Consumer<List<AssetInfo>>() {
  58. @Override
  59. public void accept(@NonNull List<AssetInfo> assets) throws Exception {
  60. assetsConsumer.accept(assets);
  61. }
  62. });
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement