A
A
Alexander2016-03-10 08:16:02
Java
Alexander, 2016-03-10 08:16:02

Android, RxJava, AsyncTask and screen rotation - how to put it all together?

Hello!
There is a main activity with fragment loading. The fragment is self-sufficient and does not transfer data to the activity. The fragment implements the simplest AsyncTask with iterating through the array and displaying the progress of the current operation in the dialog window (in the TextView we display the array element, in the ProgressBar - its number).
Is it possible, in principle, without dancing with a tambourine and a bunch of code, to translate the AsyncTask code to RxJava so that the device screen rotation is also correctly processed?
Where can I find a working example, how can this be organized?
Read this
stackoverflow.com/questions/33980194/asynctask-in-...
and this ru.stackoverflow.com/questions/486838/alertdialog-...
and here ru.stackoverflow.com/questions/470393/asynctask-%D ...
Close, but not that.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Zagaevsky, 2016-03-10
@cry_san

RxJava has mechanisms for this, such as cache();

Observable<Photo> request = service.getUserPhoto(id).cache();
Subscription sub = request.subscribe(photo -> handleUserPhoto(photo));

// перед тем, как активити пересоздаётся
sub.unsubscribe();

// когда она пересоздалась
request.subscribe(photo -> handleUserPhoto(photo));

In this case, you need to save somewhere outside the request activity, it must be the same object. This is not a silver bullet, in different cases it is necessary to act differently. In order to guarantee unsubscribing when recreating it is easier to use CompositeSubscribtion.
You can read more here: blog.danlew.net/2014/10/08/grokking-rxjava-part-4
And, it seems, there was a translation on Habré.

T
Tiberal, 2016-03-10
@Tiberal

You can wrap everything in a loader, it is tied to the life cycle
or here https://github.com/trello/RxLifecycle

F
finCoder, 2016-07-12
@finCoder

You can also save to Retaince Fragment, which will look something like this

public class RetainFragment<T> extends Fragment {

    @NonNull
    public static <T> RetainFragment<T> newInstance() {
        final RetainFragment<T> retainFragment = new RetainFragment<>();
        retainFragment.setRetainInstance(true);
        return retainFragment;
    }

    private T object;

    @NonNull
    public T getObject() {
        return object;
    }

    public void setObject(@NonNull T object) {
        this.object = object;
    }
}

Here is a good example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question