1

I'm new to the rxjava world and trying to implement the following scenario.

Basically I want to make an api call and then save the info in the database in order to the next time I launch the app it loads the data from the db. So to achieve this I created a completable for each insert in the database and then whenever it finishes it notifies me in the UI. But the thing is it never ends.

My api call:

fun getConversation(): Single<ConversationResponse>

It returns a a list of users and a list of messages

My inserts in the db:

fun insertUsers(users: List<User>) = Completable
        .create { usersDao.addUsers(users) }

fun insertMessages(messages: List<Message>) = Completable
        .create { messagesDao.addMessages(messages) }

Then I make the api call and insert the data

fun getMessagesFromApi(): Completable {

    return conversationService.getConversation()
            .flatMapCompletable {
                conversationCache.insertUsers(it.users)
                        .doOnComplete { Log.d("ConversationActivity", "Insert users") }
                        .andThen(conversationCache.insertMessages(it.messages)
                                .doOnComplete { Log.d("ConversationActivity", "Insert messages") })
            }

Then in my activity

conversationRepository.getMessagesFromApi()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : DisposableCompletableObserver() {
                override fun onStart() {
                    Log.d("ConversationActivity", "onStart")
                }

                override fun onComplete() {
                    Log.d("ConversationActivity", "onComplete")
                    mvpView?.loadedInfo()
                }

                override fun onError(e: Throwable) {
                    Log.d("ConversationActivity", "onError: $e.message")
                }
            })

In my logs I only see D/ConversationActivity: onStart

Why is this happening? Can someone give me some tips or telling me what I'm doing wrong? It would be very helpful!!!

1 Answers1

4

If you use Completable.create(), you need manually trigger onComplete()|onError() inside block passed to function. In your case you can use Completable.fromCallable() or Completable.fromAction()

ConstOrVar
  • 2,025
  • 1
  • 11
  • 14
  • So basically for each insert in my db instead of using `Completable` I create an `Action`. And when the first finishes I do the other `Completable.fromAction()`? Because I need to ensure the second is triggered after the first finishes because of the foreign keys. – António Vieira Oct 10 '18 at 08:50
  • Yes, something like that. Using `andThen()`, `flatMap()` and other operators you can chain your actions. – ConstOrVar Oct 10 '18 at 09:18