Subscribing to downstream Uni events

10 views
Skip to first unread message

Arvind Das

unread,
Dec 26, 2021, 11:04:57 AM12/26/21
to SmallRye
Hi Everyone,

Just got started with Smallrye and could implemented a few items. The builder flow is very good to create Uni's and subscribe to them.

Continuing on it, I am stuck in a situation where I would like to call my another callback if the current state is successful. I am pasting the code below to understand it easily.

Uni<PostReaction> addUserReaction(String postId, ReactionType reactionType, String userId) throws CustomException {
return PostReaction.searchByPostIdAndUserId(postId,userId)
.onItem().ifNotNull().invoke(pr->{
log.info("invoking because it is not null");
if(pr.getReactionType()!=null && !pr.getReactionType().equals(reactionType)) {
pr.setReactionType(reactionType);
pr.persist();
}
})
.onItem().ifNull().switchTo(()->{
log.info("invoking because it is null");
PostReaction postReaction = new PostReaction();
postReaction.setPostId(postId);
postReaction.setUserId(userId);
postReaction.setReactionType(reactionType);
return postReaction.persist();
});
}

Now I have another function like this to be called after only switch operation completes successfully.

public Uni<Long> updateReactionCount(String postId){
return Post.update("{$inc:{reactionCount:1}}").where("_id", new ObjectId(postId));
}


I have tried several ways, all the type of invokes and onItem execute on the upstream Uni rather than the current one. Can anyone help me out ?

Thanks,
Arvind

Arvind Das

unread,
Dec 27, 2021, 12:44:09 AM12/27/21
to SmallRye
I have solved it like this , let me know if the approach is correct .


PostReaction.searchByPostIdAndUserId(postId, userId)
                .onItem().ifNotNull().invoke(pr -> {

                    log.info("invoking because it is not null");
                    if (pr.getReactionType() != null && !pr.getReactionType().equals(reactionType)) {
                        pr.setReactionType(reactionType);
                        pr.update().subscribeAsCompletionStage();
                    }
                })
                .onItem().ifNull().switchTo(() -> {

                    log.info("invoking because it is null");
                    PostReaction postReaction = new PostReaction();
                    postReaction.setPostId(postId);
                    postReaction.setUserId(userId);
                    postReaction.setReactionType(reactionType);
                    return postReaction.persist().replaceWith(postReaction).call(() -> updateReactionCount(postId));
                });

Thanks in Advance
Arvind
Reply all
Reply to author
Forward
0 new messages