0

Unfortunately, I can't understand how to check Observable.

Depending on connection - I want to get my data from network or DB.

I have a method that checks network connection:

companion object {
        fun isConnected() : Observable<Boolean> {
            val connectivityManager = MyApplication.applicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetwork = connectivityManager.activeNetworkInfo
            val isConnectedException = activeNetwork != null && activeNetwork.isConnectedOrConnecting
            return Observable.just(isConnectedException)
        }
    }

So if it's true I want to call my network method:

override fun searchGroups(q: String): Observable<List<Group>> {
        return groupApi.searchGroups(GroupSearchRequest(q).toMap())
                .flatMap { groupResponse -> Observable.just(groupResponse.response.items) }
                .doOnNext{ groupList -> groupRepository.insertGroups(groupList)}
    }

and in the other case I want to call DB method:

override fun getGroupsFromDB(q: String): Observable<List<Group>> {
        return groupRepository.findByName(q)
    }

Here is my try to do this, but I think there is problem because of nullable interactor, but still don't know what to do.

compositeDisposable.add(
                NetworkManager.isConnected()
                        .flatMap {
                             if (it) {
                                interactor?.searchGroups(q)
                            } else {
                                interactor?.getGroupsFromDB(q)
                            }
                        }
    }
    )

enter image description here

Could anybody please help me with that ?

UPDATE

So the problem was in nullable object interactor.

Could anybody please suggest the better way to not using !! for interactor object?

enter image description here

Andrew
  • 591
  • 2
  • 12
  • 33
  • 1
    `CompositeDisposable#add()` should receive `Disposable`, but you put `Observable`. To fix that problem call `subscribe` on your `Observable` – ConstOrVar Oct 28 '18 at 20:04
  • Thanks for the answer, but there is another problem, that when I am trying to call `subscribeOn()` or `subscribe()` method where `flatMap` brackets is over - there is no options for this. There is no `subscribe()` and other methods. Do you have any idea why ? – Andrew Oct 29 '18 at 10:29
  • *Could anybody please suggest the better way to not using !!* make it not nullable – Tim Nov 02 '18 at 10:49
  • See https://stackoverflow.com/questions/45607972/why-does-smartcast-not-work-after-nullcheck/45608381#45608381. – Alexey Romanov Nov 02 '18 at 13:13

0 Answers0