Alen Lee
Alen Lee

Reputation: 2509

how to merge two Observable by key in Rxjava?

I have a Observable a

class User {
    public int userId;
    public String userName;
    public int age;
    public Boolean vip;
}

Dataset:

userId  userName  age   vip
   1       ham     21  false
   2       lily    18  false
   3       potter  38  false

Observable b

class VIP {
    public int userId;
    public Boolean vip;
}

Dataset:

userId  vip
   1   true

the expected merge result:

userId  userName  age   vip
   1       ham     21  true
   2       lily    18  false
   3       potter  38  false

As known, Rxjava has Merge, Concat, Zip, Join, but they all seems like can't do this

Upvotes: 1

Views: 293

Answers (1)

Dave Moten
Dave Moten

Reputation: 12097

If the two streams have the same order by user then you can zip them:

users.zipWith(vips, (u,v) -> new User(u.userName, u.userId, u.age, v.vip))

You could modify the u but best to prefer immutability (so create a new object).

If the two streams have different order you can use matchWith from rxjava2-extras.

Upvotes: 1

Related Questions