0

I have two objects bookmark, bookmarks, i want to pass object as parameters to Scala Templates like

return ok(views.html.bookmarks.list.render(bookmark, bookmarks));

in F.Promise,

public static F.Promise<Result> get(final String id) {
    F.Promise<Bookmark> bookmark = Bookmark.findById(id);
    F.Promise<Collection<Bookmark>> bookmarks = Bookmark.findAll();
    // here how to write the code that should pass both objects to scala template
}

How to write the return statement to pass these two objects in F.Promise without Json Result?

Sivailango
  • 514
  • 1
  • 6
  • 15

2 Answers2

1

You need to map the result of the future, and if you want to pass 2 objects out of it you can use a Tuple. You can also improve this by making the database calls concurrently with zip. When you use zip() you'll improve the efficiency of the code and automatically get a Tuple out of it.

public static F.Promise<Result> get(final String id) {
    return F.Promise.promise(() -> Bookmark.findById(id))
                    .zip(F.Promise.promise(Bookmark::findAll)) // results in a Tuple<Bookmark, Collection<Bookmark>>
                    .map(tuple -> ok(views.html.bookmarks.list.render(tuple._1, tuple._2)))
}

This doesn't take into account error handling, i.e. a Bookmark with id not being present. For that, you'll need to look at recover or recoverWith.

Steve Chaloner
  • 7,954
  • 1
  • 20
  • 38
0
   public static F.Promise<Result> index(Long id) {
F.Promise<Bookmark> futureBookmark = Bookmark.findById(id);
F.Promise<Collection<Bookmark>> futureBookmarks = Bookmark.findAll();
return futureBookmark.flatMap(new F.Function<Bookmark, F.Promise<Result>>() {
    @Override
    public F.Promise<Result> apply(final Bookmark bookmark) throws Throwable {
        return futureBookmarks.map(new F.Function<Collection<Bookmark>, Result>() {
            @Override
            public Result apply(Collection<Bookmark> bookmarks) throws Throwable {
                return ok(views.html.bookmarks.list.render(bookmark, bookmarks));
            }
        });
    }
});

}

For Java 1.7

Sivailango
  • 514
  • 1
  • 6
  • 15