@@ -0,0 +1,2644 @@
+package de.metalmatze.krautreporter.services;%0A%0Aimport android.content.Context;%0A%0Aimport java.util.List;%0A%0Aimport de.metalmatze.krautreporter.api.Api;%0Aimport de.metalmatze.krautreporter.models.Article;%0Aimport de.metalmatze.krautreporter.models.Author;%0Aimport de.metalmatze.krautreporter.models.Image;%0Aimport io.realm.Realm;%0Aimport io.realm.RealmResults;%0Aimport rx.Observable;%0Aimport rx.android.schedulers.AndroidSchedulers;%0Aimport rx.schedulers.Schedulers;%0A%0Apublic class ArticleService %7B%0A%0A    public static final String SORT_FIELD = %22order%22;%0A%0A    private Api api;%0A    private Realm realm;%0A%0A    public ArticleService(Context context, Api api) %7B%0A        this.api = api;%0A        this.realm = Realm.getInstance(context);%0A    %7D%0A%0A    public Observable%3CList%3CArticle%3E%3E getArticles() %7B%0A        RealmResults%3CArticle%3E articles = realm.where(Article.class).findAll();%0A        articles.sort(SORT_FIELD, RealmResults.SORT_ORDER_DESCENDING);%0A        return Observable.just(articles);%0A    %7D%0A%0A    public Observable%3CList%3CArticle%3E%3E updateArticles() %7B%0A        return api.request().articles()%0A                .subscribeOn(Schedulers.io())%0A                .observeOn(AndroidSchedulers.mainThread())%0A                .map(articles -%3E articles.data)%0A                .map(this::copyOrUpdateArticles);%0A    %7D%0A%0A    public Observable%3CList%3CArticle%3E%3E getArticlesOlderThan(int id) %7B%0A        return api.request().articlesOlderThan(id)%0A                .subscribeOn(Schedulers.io())%0A                .observeOn(AndroidSchedulers.mainThread())%0A                .map(articles -%3E articles.data)%0A                .map(this::copyOrUpdateArticles);%0A    %7D%0A%0A    private List%3CArticle%3E copyOrUpdateArticles(List%3CArticle%3E articles) %7B%0A        realm.beginTransaction();%0A        List%3CArticle%3E realmArticles = realm.copyToRealmOrUpdate(articles);%0A%0A        int index = 0;%0A        for (Article article : realmArticles) %7B%0A            int authorId = articles.get(index).getSerializedAuthor();%0A            Author author = realm.where(Author.class)%0A                    .equalTo(%22id%22, authorId)%0A                    .findFirst();%0A            article.setAuthor(author);%0A%0A            List%3CImage%3E serializedImages = articles.get(index).getSerializedImages().data;%0A            List%3CImage%3E realmImages = realm.copyToRealmOrUpdate(serializedImages);%0A%0A            for (Image image : realmImages) %7B%0A                article.getImages().add(image);%0A            %7D%0A%0A            index++;%0A        %7D%0A%0A        realm.commitTransaction();%0A%0A        RealmResults realmResults = realm.where(Article.class).findAll();%0A        realmResults.sort(SORT_FIELD, RealmResults.SORT_ORDER_DESCENDING);%0A%0A        return realmResults;%0A    %7D%0A%7D%0A

Create ArticleService that coordinates api and realm