Resume flowable converted to live data after screen rotation

前端 未结 1 1620
北海茫月
北海茫月 2021-01-24 09:28

Say I have an activity like this:

public class TestActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceStat         


        
相关标签:
1条回答
  • 2021-01-24 09:37

    Thanks to Svyatoslav Lebeckiy over at Android United Slack channel who pointed out BehaviorSubject and BehaviorProcessor to me and proposed an idea on how to fix this.

    I changed my view model to:

    class TestViewModel extends ViewModel {
    
        private LiveData<String> countdown;
    
        LiveData<String> getCountdown() {
            if (countdown == null) {
                countdown = LiveDataReactiveStreams.fromPublisher(startCountdown());
            }
            return countdown;
        }
    
        private static Flowable<String> startCountdown() {
            final BehaviorProcessor<String> processor = BehaviorProcessor.create();
            Flowable.concat(
                    Flowable.just("Falcon Heavy rocket will launch in..."),
                    Flowable.intervalRange(0, 10, 3, 1, TimeUnit.SECONDS)
                            .map(x -> String.valueOf(10 - x)),
                    Flowable.timer(1, TimeUnit.SECONDS)
                            .map(ignored -> "Lift off!")
            ).subscribe(processor);
            return processor;
        }
    }
    

    This way I can start the countdown only once in getCountdown and the BehaviorProcessor created in startCountdown takes care of delivering the last and subsequently emitted values to its subscribers (LiveData in this case).

    Since LiveDataReactiveStreams needs a Flowable, it's convenient to use a BehaviorProcessor instead of BehaviorSubject here.

    0 讨论(0)
提交回复
热议问题