0

I'm using RxKotlin together with Retrofit 2

I'm trying figure out how to have dynamic list of observers on a single operation.

The first observer should trigger the operation, and all additional observers should wait until the operation complete/fails

Once the operation complete,I need to make data manipulation (Store in cache/Memory) and then notify all the observers.

Here's what I did:

class UserManager
{
    val observers = ArrayList<Observer<ArrayList<User>>>()
    var isFetchingUsers = false

    fun getUsers(observer: Observer<ArrayList<User>>)
    {
        observers.add(observer)

        if (isFetchingUsers)
        {
            return
        }

        api.getUserList.observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<UserListResponse>
        {
            override fun onNext(response: UserListResponse)
            {
                // Do some manipulations on the response and notify all

                observers.forEach {
                    it.onNext(response.getUsers())
                }
            }

            override fun onError(e: Throwable)
            {
                observers.forEach {
                    it.onError(Throwable())
                }
            }

            override fun onComplete()
            {
                isFetchingUsers = false
                observers.clear()
            }

            override fun onSubscribe(d: Disposable)
            {
            }
        })
    }
}

Here's Retrofit observable creation (this one is in Java..)

   /**
     * Get users
     */
    public Observable<UserListResponse> getUserList()
    {
        return mService.getUserList().subscribeOn(Schedulers.io());
    }

I'm sure there's a better way for doing this

Thanks!

dor506
  • 5,246
  • 9
  • 44
  • 79

1 Answers1

0

You can use the share() operator on an observable. Only the first subscription will cause the observable to do its creation process. Once the last subscriber is unsubscribed, the observable will do its destruction process.

Observable<Long> v;
...
Observable<Long> sharedObservable = v
  .doOnSubscribe( () -> logger.debug("subscribe") )
  .doOnUnsubscribe( () -> logger.debug("unsubscribe") )
  .share();

...
Subscription v1 = sharedObservable.subscribe();
Subscription v2 = sharedObservable.subscribe();
...
v1.unsubscribe();
v2.unsubscribe();

You will see that the subscribe operation only happens once. You should see that only one subscription operation happens to the original observable, and only one unsubscription.

Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42