问题
I have this code:
public void testGetBlob() throws RequestException {
TestData.getNewApplication().flatMap(testApplication -> {
Client.initialize(testApplication.getAppId(), testApplication.getApiToken(), testApplication.getMasterKey());
assertNotNull(testApplication.getApiToken());
assertNotNull(testApplication.getAppId());
assertNotNull(testApplication.getMasterKey());
Entity entity = new Entity("Todo");
return entity.create();
}).flatMap(entity -> entity.setBlobProperty("text", "Hello world!".getBytes("UTF-8")))
.flatMap(isSuccess -> {
if(isSuccess) {
// need to access `entity` at this point
return Single.just(isSuccess);
} else {
return Single.just(false);
}
}).subscribe(success -> {
Browser.getWindow().getConsole().log("Blob created");
finishTest();
}, error -> {
Browser.getWindow().getConsole().error(error.getMessage());
fail();
});
delayTestFinish(5000);
}
In the code above what I need to do is to be able to access the entity
object at the point in the comment. How can it be done?
回答1:
Between one operator and another you can only emit one object type. In your situation you are emitting a boolean value, but you also want to have access to the Entity object. The solution is to wrap both values (Entity object and boolean value) in a single class and emit that class.
Create a class to wrap the emission of Entity and the result of setBlobProperty.
class Pair {
private final Entity entity;
private final boolean success;
private Pair(Entity entity, boolean success) {
this.entity = entity;
this.success = success;
}
public Entity getEntity() {
return entity;
}
public boolean isSuccess() {
return success;
}
}
Then change your code to emit that class:
public void testGetBlob() throws RequestException {
TestData.getNewApplication().flatMap(testApplication -> {
// ...
return entity.create();
}).flatMap(entity ->
entity.setBlobProperty("text", "Hello world!".getBytes("UTF-8"))
// 1. Flat map the setBlobProperty call and emit a Pair with the entity and result
.flatMap(isSuccess -> Single.just(new Pair(entity, isSuccess)))
)
.flatMap(pair -> {
if(pair.isSuccess()) {
// 2. entity is available here via pair.getEntity()
return Single.just(isSuccess);
} else {
return Single.just(false);
}
}).subscribe(success -> {
// ...
}
}
Ps: instead of creating your own Pair class, check one of the options from this thread. If you are using Kotlin, there is a Pair class.
来源:https://stackoverflow.com/questions/57541365/what-are-the-ways-to-merge-to-observables-singles