I have the following code:

interface UsersApi {
  fun getUsers() : Single<List<UserTO>>
  fun getPosts(postId: String) : Single<PostTO>
}
data class UserTO(val name: String, postIds: List<String>)
data class PostTO(val title: String, val content: String)
data class User(val name: String, val posts: List<Post>)
data class Post(val title: String, content: String)

I am trying to write a repository class with a method that returns

Single<List<User>>

But I have no idea how to do it, since I need access to earlier objects in the stream and also the Single is confusing things.

I am pretty sure I have to start with a call to getUsers followed by a flatmap, but then the things get confusing.

Any help?

up vote 1 down vote accepted

If you want to load your users from the API and for each user load their posts then you could do something like the following.

flattenAsFlowable allows you to iterate each UserTO from your api response. With this you can extract their postIds and map to the User object.

Flowable.fromIterable allows you to iterate over the postIds collection and perform the api call for each post.

class MyRepository(private val api: UsersApi) {

    fun getUsers(): Single<List<User>> {
        return api.getUsers()
            .flattenAsFlowable { it }
            .flatMapSingle { loadUserPosts(it) }
            .toList()
    }

    private fun loadUserPosts(user: UserTO): Single<User> {
        return loadPosts(user.postIds)
            .map { User(name = user.name, posts = it) }
    }

    private fun loadPosts(postIds: List<String>): Single<List<Post>> {
        return Flowable.fromIterable(postIds)
            .flatMapSingle { api.getPosts(it) }
            .map { Post(title = it.title, content = it.content) }
            .toList()
    }
}
  • thank you, straightforward and elegant. – A. Student Sep 13 at 8:06

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.