Git Product home page Git Product logo

rxgroups's Introduction

RxGroups

Build Status

RxGroups lets you group RxJava Observables together in groups and tie them to your Android lifecycle. This is especially useful when used with Retrofit.

For simple scenarios you can probably just let the original request be cancelled and fire a new one. However it's easy to see how this becomes a problem in more complex situations.

Let's say your user is submitting a payment. You'll probably want to guarantee that you can reattach to the same in-flight or completed request after rotating the screen or leaving the Activity and returning later.

RxGroups will also automatically prevent events from being delivered to your Activity or Fragment before onResume() and after onPause(). If that happens, they will be automatically cached in memory and delivered once the user returns to your screen. If they never return, the memory is then reclaimed automatically after onDestroy().

Usage

  1. Add a GroupLifecycleManager field to your Activity, Fragment, Dialog, etc. and call its respective lifecycle methods according to your own (eg.: onPause, onResume, onDestroy, etc.);
  2. Annotate your ResubscriptionObserver with @AutoResubscribe and use method resubscriptionTag() to tell RxGroups what tag it should use for reattaching your Observer to it Observable automatically. To use RxGroups with Kotlin don't forget to annotate fields with @JvmField.
  3. Before subscribing to your Observable, compose it with observableGroup.transform() to define a tag for that Observable;

Example

public class MyActivity extends Activity {
  private static final String OBSERVABLE_TAG = "arbitrary_tag";
  private TextView output;
  private FloatingActionButton button;
  private GroupLifecycleManager groupLifecycleManager;
  private ObservableGroup observableGroup;
  private Observable<Long> observable = Observable.interval(1, 1, TimeUnit.SECONDS);

  // The Observer field must be public, otherwise RxGroups can't access it
  @AutoResubscribe public final ResubscriptionObserver<Long> observer = new ResubscriptionObserver<Long>() {
    @Override public void onCompleted() {
      Log.d(TAG, "onCompleted()");
    }

    @Override public void onError(Throwable e) {
      Log.e(TAG, "onError()", e);
    }

    @Override public void onNext(Long l) {
      output.setText(output.getText() + " " + l);
    }

    @Override public Object resubscriptionTag() {
      return OBSERVABLE_TAG;
    }
  };

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    output = (TextView) findViewById(R.id.txt_output);
    button = (FloatingActionButton) findViewById(R.id.fab);
    SampleApplication application = (SampleApplication) getApplication();
    ObservableManager manager = application.observableManager();
    groupLifecycleManager = GroupLifecycleManager.onCreate(manager, savedInstanceState, this);
    observableGroup = groupLifecycleManager.group();

    button.setOnClickListener(v -> observable
        .compose(observableGroup.<Long>transform(OBSERVABLE_TAG))
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(observer));
  }

  @Override protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    groupLifecycleManager.onSaveInstanceState(outState);
  }

  @Override protected void onResume() {
    super.onResume();
    groupLifecycleManager.onResume();
  }

  @Override protected void onPause() {
    super.onPause();
    groupLifecycleManager.onPause();
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    groupLifecycleManager.onDestroy(this);
  }
}

Optional: If you don't want to use a ResubscriptionObserver with @AutoResubscribe just use a regular Observer anonymous class with a public method called resubscriptionTag(). Eg.:

@AutoResubscribe public final Observer<Long> observer = new Observer<Long>() {
    @Override public void onCompleted() {
    }

    @Override public void onError(Throwable e) {
    }

    @Override public void onNext(Long l) {
    }

    public Object resubscriptionTag() {
      return Arrays.asList("tag1", "tag2", "tag3");
    }
  };

If the method doesn't exist or is not public, RxGroups will throw a RuntimeException letting you know. You can use any Object tag for your Observer, including arrays and List, In that case, it will associate the Observer with all the tags in the collection, allowing you to share the same Observer with multiple Observables.

Download with Gradle

compile 'com.airbnb:rxgroups-android:0.3.5'

Check out the Sample app for more details and a complete example!

Snapshots of the development version are available in Sonatype's snapshots repository.

License

Copyright 2016 Airbnb, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

rxgroups's People

Contributors

apsaliya avatar benschwab avatar elihart avatar felipecsl avatar jeuler avatar lucas34 avatar rossbacher avatar supercairos avatar ubiratansoares avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rxgroups's Issues

RxJava2?

Hi!
Do you have any plans for migrating or any guides for using it with RxJava2?
Since RxJava2 released 3 months ago, I think it soon will be a major blocker for using this library.

OnErrorNotImplemented exception

If an exception is thrown from resubscriptionTag(), then RxGroups will throw with OnErrorNotImplementedException. We should probably implement onError and provide a more meaningful message. Here's the current stacktrace:

java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
   at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:112)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5254)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: rx.exceptions.OnErrorNotImplementedException: Exception thrown from 'resubscriptionTag()'
   at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(InternalObservableUtils.java:386)
   at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(InternalObservableUtils.java:383)
   at rx.internal.util.ActionSubscriber.onError(ActionSubscriber.java:44)
   at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:153)
   at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:115)
   at rx.internal.operators.OnSubscribeFilter$FilterSubscriber.onError(OnSubscribeFilter.java:90)
   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:273)
   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:216)
   at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107)
   at android.os.Handler.handleCallback(Handler.java:739) 
   at android.os.Handler.dispatchMessage(Handler.java:95) 
   at android.os.Looper.loop(Looper.java:135) 
   at android.app.ActivityThread.main(ActivityThread.java:5254) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at java.lang.reflect.Method.invoke(Method.java:372) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Caused by: java.lang.RuntimeException: Exception thrown from 'resubscriptionTag()'
   at com.airbnb.rxgroups.LifecycleResubscription$4.call(LifecycleResubscription.java:109)
   at com.airbnb.rxgroups.LifecycleResubscription$4.call(LifecycleResubscription.java:98)
   at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:231)
   at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:228)
   at rx.Observable.unsafeSubscribe(Observable.java:10142)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:248)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:148)
   at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:77)
   at rx.internal.operators.OnSubscribeFilter$FilterSubscriber.onNext(OnSubscribeFilter.java:76)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.emitScalar(OperatorMerge.java:395)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.tryEmit(OperatorMerge.java:355)
   at rx.internal.operators.OperatorMerge$InnerSubscriber.onNext(OperatorMerge.java:846)
   at rx.internal.operators.OnSubscribeFromIterable$IterableProducer.slowPath(OnSubscribeFromIterable.java:117)
   at rx.internal.operators.OnSubscribeFromIterable$IterableProducer.request(OnSubscribeFromIterable.java:89)
   at rx.Subscriber.setProducer(Subscriber.java:211)
   at rx.internal.operators.OnSubscribeFromIterable.call(OnSubscribeFromIterable.java:63)
   at rx.internal.operators.OnSubscribeFromIterable.call(OnSubscribeFromIterable.java:34)
   at rx.Observable.unsafeSubscribe(Observable.java:10142)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:248)
   at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:148)
   at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:77)
   at rx.internal.util.ScalarSynchronousObservable$ScalarAsyncProducer.call(ScalarSynchronousObservable.java:200)
   at rx.internal.util.ScalarSynchronousObservable$2$1.call(ScalarSynchronousObservable.java:114)
   at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
 at java.util.concurrent.FutureTask.run(FutureTask.j

0.3.5: Observable not being cached and fragments / activities being leaked

Hi there!

First, thank you for making this library, it looks like it will solve many issues with mobile applications when it comes to doing asynchronous work and sudden configuration changes.

However, I've run into an issue and I am not entirely sure what I am doing incorrectly as I believe I followed the sample closely

Introduction to app

Simple app that uses Retrofit to fetch a list of users. Once fetched, these users are displayed on a RecyclerView that is apart of a fragment

Summary of problems

My onStart method within the fragment looks like this

  @Override
    public void onStart() {
        super.onStart();
        if(mUsers == null && !mGroupLifecycleManager.hasObservable(TAG))
            loadUsers();
    }

So it checks if we do not have users already and the manager does not have the observable
On a configuration change, the hasObservable call always returns false even though I am forwarding the appropriate life cycle calls

Once the task is done, it calls the following method in onNext

private void displayUsers(){
        showContent();
        UserAdapter userAdapter = new UserAdapter(mUsers);
        mRecyclerView.setAdapter(userAdapter);
        String randomString = getString(R.string.app_name);
    }

When I rotate the device whilst the task is ongoing, I will eventually I get the following error in my logcat

11-08 23:06:41.416 763-763/com.ersen.rxgroupissue I/UsersFragment: onError java.lang.IllegalStateException: Fragment UsersFragment{2fcd9c4} not attached to Activity
                                                                       at android.support.v4.app.Fragment.getResources(Fragment.java:648)
                                                                       at android.support.v4.app.Fragment.getString(Fragment.java:670)
                                                                       at com.ersen.rxgroupissue.fragments.UsersFragment.displayUsers(UsersFragment.java:107)
                                                                       at com.ersen.rxgroupissue.fragments.UsersFragment.access$200(UsersFragment.java:37)
                                                                       at com.ersen.rxgroupissue.fragments.UsersFragment$1.onNext(UsersFragment.java:131)
                                                                       at com.ersen.rxgroupissue.fragments.UsersFragment$1.onNext(UsersFragment.java:110)
                                                                       at rx.internal.util.ObserverSubscriber.onNext(ObserverSubscriber.java:34)
                                                                       at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:134)
                                                                       at rx.internal.operators.OperatorSubscribeOn$1$1.onNext(OperatorSubscribeOn.java:53)
                                                                       at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:227)
                                                                       at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I decided to look at a heap snapshot and I encountered that I had many MainAcitivity and UserFragment instances left in memory after configuration change. This is probably the cause of the above exception, somehow it called the method on a dead leftover instance of the fragment.

Here is a link to the project which replicates the issue I am having. I would be very grateful if you could look over this.

https://www.dropbox.com/s/ooipzvxqxeobipi/RxGroupIssue.rar?dl=0

Note that I forward the lifecycles to GroupLifecycleManager in the BaseFragment class

Any more information needed, let me know

Cheers!

ResubscriptionObserver in MVP

Does the ResubscriptionObserver with @AutoResubscribe have to be inside the activity or can I put it somewhere else like into the Presenter?

I am injecting the GroupLifecycleManager into the presenter to use it and of course calling the life cycle methods inside the activity.

Rx : fromAsync has been removed in newer version

Hi,

The method fromAsync() as been removed in Rx version 1.2.0. It has been replaced by fromEmitter.
However, They are still in discussion about the signature and the interface name.

Even if we replace now the fromAsync with the fromEmitter, I'm scare we need to do it again for the next Rx release. I think we should avoid using the experimental operator in libraries.

Feel free to late me know what do you think.
I can make a PR.

Lucas.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.