These are chat archives for ReactiveX/RxJava

13th
Sep 2016
Toon Sevrin
@toonsevrin
Sep 13 2016 16:30
@Dorus Nooooo ReactiveX/RxJava#4545
Vadym
@dragantl
Sep 13 2016 18:44

Can anyone suggest a more elegant way of doing the following:

  • I have a mixin class that monitors bootstrap and authentication states for Activity and Fragment. The mixin then emits an authenticated session into a BehaviorSubject, which can be accessed via a public method.
  • Once the session becomes active, an API client can be requested using the session.
  • Within a fragment, I create a BehaviorSubject and emit the client every time I acquire it.
  • The fragment itself is responsible for periodically fetching a list of entries from the client.
  • The fetching is setup in onResume and demolished in onPause

Rough code:

public class MyFrag extends RxFragment {
    private AccountMixin mAccountMixin = null;
    private AuthenticatedSession mSession = null;
    protected ApiClient mClient = null;
    private BehaviorSubject<ApiClient> mClientSubject = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mClientSubject = BehaviorSubject.create();
    }

    @Override
    public void onStart() {
        super.onStart();

        mAccountMixin.getAuthenticatedAccountObservable()
                .compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.STOP))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onSession);
    }

    private void onSession(final AuthenticatedSession session) {
        mSession = session;
        mClient = ApiProvider.requestClient(session);
        mClientSubject.onNext(mClient);
    }

    @Override
    public void onResume() {
        super.onResume();

        final Observable<List<EntryInfo>> entryObservable = Observable
                .interval(5, TimeUnit.SECONDS)
                .switchMap(tick -> mClient.getEntries())
                ...;

        mClientSubject
                .filter(client -> client != null)
                .switchMap(c -> entryObservable)
                .compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.PAUSE))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::updateEntryList);
    }
}

Obviously, the code is a mess. However, I cannot see how to make it more elegant. The AccountSession can be emitted at any point in time (e.g., during Fragment's start, resume, pause, or stop events). However, I need to start list initial load and refresh only during onResume state. I feel like I'm just approaching this thing from the wrong angle. Any suggestions?

Dorus
@Dorus
Sep 13 2016 18:46
@toonsevrin Nice. I guess we should have checked the latest snapshot too :)
Dorus
@Dorus
Sep 13 2016 23:35
This message was deleted