From RxJava2, How can I compare and filter two observables if the values are equal? The Next CEO of Stack OverflowRxJava2 How to share an observable with two other observer, and merge it back to a subscriberHow to chain two Completable in RxJava2How to chain observables in rxjava2RxJava and long running listenerRxJava2 - Concat multiple observables, prevent execution if first element foundRxjava2 - how to cache ObservableHow to preserve informations about original observable on RxJava2RxJava2 : Filtering a List<Object> in an Observablegetting java.io.InterruptedIOException while implementing instant search in android using RxJava2 and RetrofitHow to compare items in two observables and then filter based on matches in RxJava2?

Why did we only see the N-1 starfighters in one film?

Can the Reverse Gravity spell affect the Meteor Swarm spell?

Unreliable Magic - Is it worth it?

Are there languages with no euphemisms?

Should I tutor a student who I know has cheated on their homework?

How long to clear the 'suck zone' of a turbofan after start is initiated?

How to Reset Passwords on Multiple Websites Easily?

Customer Requests (Sometimes) Drive Me Bonkers!

Describing a person. What needs to be mentioned?

Too much space between section and text in a twocolumn document

If I blow insulation everywhere in my attic except the door trap, will heat escape through it?

How do we know the LHC results are robust?

Why does C# sound extremely flat when saxophone is tuned to G?

Science fiction (dystopian) short story set after WWIII

Return of the Riley Riddles in Reverse

What can we do to stop prior company from asking us questions?

When airplanes disconnect from a tanker during air to air refueling, why do they bank so sharply to the right?

Fastest way to shutdown Ubuntu Mate 18.10

How can I open an app using Terminal?

Term for the "extreme-extension" version of a straw man fallacy?

How do spells that require an ability check vs. the caster's spell save DC work?

Trouble understanding the speech of overseas colleagues

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

Why does standard notation not preserve intervals (visually)



From RxJava2, How can I compare and filter two observables if the values are equal?



The Next CEO of Stack OverflowRxJava2 How to share an observable with two other observer, and merge it back to a subscriberHow to chain two Completable in RxJava2How to chain observables in rxjava2RxJava and long running listenerRxJava2 - Concat multiple observables, prevent execution if first element foundRxjava2 - how to cache ObservableHow to preserve informations about original observable on RxJava2RxJava2 : Filtering a List<Object> in an Observablegetting java.io.InterruptedIOException while implementing instant search in android using RxJava2 and RetrofitHow to compare items in two observables and then filter based on matches in RxJava2?










0















I am new to RxJava2.



I am trying to get a list of Transaction object both from cache and from server.
I want to compare the server value to cache value and if the server value is the same, then ignore it.



I was able to do it easily using .scan() because we can return null and when null is returned from the .scan() the value got ignored(filtered).



RxJava 1



private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.scan((p1, p2) ->
if (p1 == null && p2 != null)
return p2;
else if (p1 != null && !isListSame(p1, p2))
return p2;
else
return null;

);



With RxJava 2, since I cannot return null anymore, things are not easy.



RxJava 2



 private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
return Observable.concat(
getTransactionsFromCache(),
getTransactionsFromServer()
)
.map(FilterObject::new)
.scan((filterObject1, filterObject2) ->
List<Transaction> p1 = (List<Transaction>)filterObject1.value;
List<Transaction> p2 = (List<Transaction>)filterObject2.value;

if (p1.size() == 0 && p2.size() > 0)
return filterObject2;
else if (!isListSame(p1, p2))
return filterObject2;
else
filterObject2.filter = true;
return filterObject2;

)
.filter(filterObject -> !filterObject.filter)
.map(filterObject -> (List<Transaction>)filterObject.value);



Where FilterObject is:



public class FilterObject 
public Object value;
public boolean filter;

public FilterObject(Object value)
this.value = value;





Even though I can achieve the same thing using above method, it seems very ugly. Also I had to include two maps which might not be so performance friendly.



Is there a simple/clean way to achieve what I want?










share|improve this question


























    0















    I am new to RxJava2.



    I am trying to get a list of Transaction object both from cache and from server.
    I want to compare the server value to cache value and if the server value is the same, then ignore it.



    I was able to do it easily using .scan() because we can return null and when null is returned from the .scan() the value got ignored(filtered).



    RxJava 1



    private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
    return Observable.concat(
    getTransactionsFromCache(),
    getTransactionsFromServer()
    )
    .scan((p1, p2) ->
    if (p1 == null && p2 != null)
    return p2;
    else if (p1 != null && !isListSame(p1, p2))
    return p2;
    else
    return null;

    );



    With RxJava 2, since I cannot return null anymore, things are not easy.



    RxJava 2



     private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
    return Observable.concat(
    getTransactionsFromCache(),
    getTransactionsFromServer()
    )
    .map(FilterObject::new)
    .scan((filterObject1, filterObject2) ->
    List<Transaction> p1 = (List<Transaction>)filterObject1.value;
    List<Transaction> p2 = (List<Transaction>)filterObject2.value;

    if (p1.size() == 0 && p2.size() > 0)
    return filterObject2;
    else if (!isListSame(p1, p2))
    return filterObject2;
    else
    filterObject2.filter = true;
    return filterObject2;

    )
    .filter(filterObject -> !filterObject.filter)
    .map(filterObject -> (List<Transaction>)filterObject.value);



    Where FilterObject is:



    public class FilterObject 
    public Object value;
    public boolean filter;

    public FilterObject(Object value)
    this.value = value;





    Even though I can achieve the same thing using above method, it seems very ugly. Also I had to include two maps which might not be so performance friendly.



    Is there a simple/clean way to achieve what I want?










    share|improve this question
























      0












      0








      0








      I am new to RxJava2.



      I am trying to get a list of Transaction object both from cache and from server.
      I want to compare the server value to cache value and if the server value is the same, then ignore it.



      I was able to do it easily using .scan() because we can return null and when null is returned from the .scan() the value got ignored(filtered).



      RxJava 1



      private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
      return Observable.concat(
      getTransactionsFromCache(),
      getTransactionsFromServer()
      )
      .scan((p1, p2) ->
      if (p1 == null && p2 != null)
      return p2;
      else if (p1 != null && !isListSame(p1, p2))
      return p2;
      else
      return null;

      );



      With RxJava 2, since I cannot return null anymore, things are not easy.



      RxJava 2



       private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
      return Observable.concat(
      getTransactionsFromCache(),
      getTransactionsFromServer()
      )
      .map(FilterObject::new)
      .scan((filterObject1, filterObject2) ->
      List<Transaction> p1 = (List<Transaction>)filterObject1.value;
      List<Transaction> p2 = (List<Transaction>)filterObject2.value;

      if (p1.size() == 0 && p2.size() > 0)
      return filterObject2;
      else if (!isListSame(p1, p2))
      return filterObject2;
      else
      filterObject2.filter = true;
      return filterObject2;

      )
      .filter(filterObject -> !filterObject.filter)
      .map(filterObject -> (List<Transaction>)filterObject.value);



      Where FilterObject is:



      public class FilterObject 
      public Object value;
      public boolean filter;

      public FilterObject(Object value)
      this.value = value;





      Even though I can achieve the same thing using above method, it seems very ugly. Also I had to include two maps which might not be so performance friendly.



      Is there a simple/clean way to achieve what I want?










      share|improve this question














      I am new to RxJava2.



      I am trying to get a list of Transaction object both from cache and from server.
      I want to compare the server value to cache value and if the server value is the same, then ignore it.



      I was able to do it easily using .scan() because we can return null and when null is returned from the .scan() the value got ignored(filtered).



      RxJava 1



      private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
      return Observable.concat(
      getTransactionsFromCache(),
      getTransactionsFromServer()
      )
      .scan((p1, p2) ->
      if (p1 == null && p2 != null)
      return p2;
      else if (p1 != null && !isListSame(p1, p2))
      return p2;
      else
      return null;

      );



      With RxJava 2, since I cannot return null anymore, things are not easy.



      RxJava 2



       private Observable<List<Transaction>> getTransactionsFromCacheAndServer() 
      return Observable.concat(
      getTransactionsFromCache(),
      getTransactionsFromServer()
      )
      .map(FilterObject::new)
      .scan((filterObject1, filterObject2) ->
      List<Transaction> p1 = (List<Transaction>)filterObject1.value;
      List<Transaction> p2 = (List<Transaction>)filterObject2.value;

      if (p1.size() == 0 && p2.size() > 0)
      return filterObject2;
      else if (!isListSame(p1, p2))
      return filterObject2;
      else
      filterObject2.filter = true;
      return filterObject2;

      )
      .filter(filterObject -> !filterObject.filter)
      .map(filterObject -> (List<Transaction>)filterObject.value);



      Where FilterObject is:



      public class FilterObject 
      public Object value;
      public boolean filter;

      public FilterObject(Object value)
      this.value = value;





      Even though I can achieve the same thing using above method, it seems very ugly. Also I had to include two maps which might not be so performance friendly.



      Is there a simple/clean way to achieve what I want?







      rx-java2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 16:24









      jclovajclova

      2,244124169




      2,244124169






















          2 Answers
          2






          active

          oldest

          votes


















          1














          I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.



          However, in your particular case you never emit an empty list, except maybe for the first output.



          (I am using String instead Transaction, shouldn't matter)



          private Observable<List<String>> getTransactionsFromCacheAndServer() 
          return Observable.concat(
          getTransactionsFromCache(),
          getTransactionsFromServer()
          )
          .filter(list -> !list.isEmpty())
          // If you prefer a consistent empty list over the first
          // empty list emission getting filtered
          .startWith((List<String>) Collections.EMPTY_LIST)
          // Newly emitted value cannot be empty, it only depends only on the comparison
          .distinctUntilChanged(this::isListSame);



          That's the closest I could get with as few operators as possible. Hope it solves your problem.






          share|improve this answer























          • Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

            – jclova
            Mar 22 at 19:58


















          0














          Based on andras' answer, I modified little bit to achieve what I want.



          private Observable<List<String>> getTransactionsFromCacheAndServer() 
          return Observable.concat(
          getTransactionsFromCache(),
          getTransactionsFromServer()
          )
          .filter(list -> !list.isEmpty())
          .distinctUntilChanged(this::isListSame)
          .switchIfEmpty(Observable.just(new ArrayList<>()));




          Andreas' answer will always receive an empty list and then a real data.



          My solution above will receive:

          1. Data from cache (and then data from server if different)

          2. Empty list if both cache and server returns Empty list.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285017%2ffrom-rxjava2-how-can-i-compare-and-filter-two-observables-if-the-values-are-equ%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.



            However, in your particular case you never emit an empty list, except maybe for the first output.



            (I am using String instead Transaction, shouldn't matter)



            private Observable<List<String>> getTransactionsFromCacheAndServer() 
            return Observable.concat(
            getTransactionsFromCache(),
            getTransactionsFromServer()
            )
            .filter(list -> !list.isEmpty())
            // If you prefer a consistent empty list over the first
            // empty list emission getting filtered
            .startWith((List<String>) Collections.EMPTY_LIST)
            // Newly emitted value cannot be empty, it only depends only on the comparison
            .distinctUntilChanged(this::isListSame);



            That's the closest I could get with as few operators as possible. Hope it solves your problem.






            share|improve this answer























            • Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

              – jclova
              Mar 22 at 19:58















            1














            I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.



            However, in your particular case you never emit an empty list, except maybe for the first output.



            (I am using String instead Transaction, shouldn't matter)



            private Observable<List<String>> getTransactionsFromCacheAndServer() 
            return Observable.concat(
            getTransactionsFromCache(),
            getTransactionsFromServer()
            )
            .filter(list -> !list.isEmpty())
            // If you prefer a consistent empty list over the first
            // empty list emission getting filtered
            .startWith((List<String>) Collections.EMPTY_LIST)
            // Newly emitted value cannot be empty, it only depends only on the comparison
            .distinctUntilChanged(this::isListSame);



            That's the closest I could get with as few operators as possible. Hope it solves your problem.






            share|improve this answer























            • Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

              – jclova
              Mar 22 at 19:58













            1












            1








            1







            I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.



            However, in your particular case you never emit an empty list, except maybe for the first output.



            (I am using String instead Transaction, shouldn't matter)



            private Observable<List<String>> getTransactionsFromCacheAndServer() 
            return Observable.concat(
            getTransactionsFromCache(),
            getTransactionsFromServer()
            )
            .filter(list -> !list.isEmpty())
            // If you prefer a consistent empty list over the first
            // empty list emission getting filtered
            .startWith((List<String>) Collections.EMPTY_LIST)
            // Newly emitted value cannot be empty, it only depends only on the comparison
            .distinctUntilChanged(this::isListSame);



            That's the closest I could get with as few operators as possible. Hope it solves your problem.






            share|improve this answer













            I don't think there is a generic solution to this problem, since an empty list and a list that needs to be filtered (which happens to be empty in all cases) are two different things (the output of the scan) and needs to be handled differently.



            However, in your particular case you never emit an empty list, except maybe for the first output.



            (I am using String instead Transaction, shouldn't matter)



            private Observable<List<String>> getTransactionsFromCacheAndServer() 
            return Observable.concat(
            getTransactionsFromCache(),
            getTransactionsFromServer()
            )
            .filter(list -> !list.isEmpty())
            // If you prefer a consistent empty list over the first
            // empty list emission getting filtered
            .startWith((List<String>) Collections.EMPTY_LIST)
            // Newly emitted value cannot be empty, it only depends only on the comparison
            .distinctUntilChanged(this::isListSame);



            That's the closest I could get with as few operators as possible. Hope it solves your problem.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 22 at 7:11









            andrasandras

            716418




            716418












            • Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

              – jclova
              Mar 22 at 19:58

















            • Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

              – jclova
              Mar 22 at 19:58
















            Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

            – jclova
            Mar 22 at 19:58





            Wow, it is the coolest operator-combo I've seen to achieve what I want. Thank you.

            – jclova
            Mar 22 at 19:58













            0














            Based on andras' answer, I modified little bit to achieve what I want.



            private Observable<List<String>> getTransactionsFromCacheAndServer() 
            return Observable.concat(
            getTransactionsFromCache(),
            getTransactionsFromServer()
            )
            .filter(list -> !list.isEmpty())
            .distinctUntilChanged(this::isListSame)
            .switchIfEmpty(Observable.just(new ArrayList<>()));




            Andreas' answer will always receive an empty list and then a real data.



            My solution above will receive:

            1. Data from cache (and then data from server if different)

            2. Empty list if both cache and server returns Empty list.






            share|improve this answer



























              0














              Based on andras' answer, I modified little bit to achieve what I want.



              private Observable<List<String>> getTransactionsFromCacheAndServer() 
              return Observable.concat(
              getTransactionsFromCache(),
              getTransactionsFromServer()
              )
              .filter(list -> !list.isEmpty())
              .distinctUntilChanged(this::isListSame)
              .switchIfEmpty(Observable.just(new ArrayList<>()));




              Andreas' answer will always receive an empty list and then a real data.



              My solution above will receive:

              1. Data from cache (and then data from server if different)

              2. Empty list if both cache and server returns Empty list.






              share|improve this answer

























                0












                0








                0







                Based on andras' answer, I modified little bit to achieve what I want.



                private Observable<List<String>> getTransactionsFromCacheAndServer() 
                return Observable.concat(
                getTransactionsFromCache(),
                getTransactionsFromServer()
                )
                .filter(list -> !list.isEmpty())
                .distinctUntilChanged(this::isListSame)
                .switchIfEmpty(Observable.just(new ArrayList<>()));




                Andreas' answer will always receive an empty list and then a real data.



                My solution above will receive:

                1. Data from cache (and then data from server if different)

                2. Empty list if both cache and server returns Empty list.






                share|improve this answer













                Based on andras' answer, I modified little bit to achieve what I want.



                private Observable<List<String>> getTransactionsFromCacheAndServer() 
                return Observable.concat(
                getTransactionsFromCache(),
                getTransactionsFromServer()
                )
                .filter(list -> !list.isEmpty())
                .distinctUntilChanged(this::isListSame)
                .switchIfEmpty(Observable.just(new ArrayList<>()));




                Andreas' answer will always receive an empty list and then a real data.



                My solution above will receive:

                1. Data from cache (and then data from server if different)

                2. Empty list if both cache and server returns Empty list.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 22 at 21:21









                jclovajclova

                2,244124169




                2,244124169



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285017%2ffrom-rxjava2-how-can-i-compare-and-filter-two-observables-if-the-values-are-equ%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현