LiveDataReactiveStreams:将Flowable转换为LiveData不起作用

时间:2018-11-16 07:40:26

标签: android rx-java rx-java2 android-architecture-components android-livedata

我正在尝试将Flowable转换为LiveData并在活动中进行观察。我的Flowable发出具有恒定延迟的值, 但是我将其转换为Flowable的LiveData根本没有在其观察者中接收任何值。我创建了一个示例代码来 演示问题

活动

    public class MyrActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
            myViewModel.init();
            myViewModel.getListLiveData().observe(this, new Observer<List<String>>() {
                @Override
                public void onChanged(@Nullable List<String> strings) {
                    Timber.d("value received in live data observer: %s", strings);
                    // This callback never get called
                    for (String string : strings) {
                        Timber.d(string);
                    }
                }
            });

        }
    }

ViewModel类

     static class MyViewModel extends ViewModel{
            LiveData<List<String>> mListLiveData;
            PublishProcessor<String> mStringPublishProcessor = PublishProcessor.create();

            public void init() {
                mListLiveData = LiveDataReactiveStreams.fromPublisher(mStringPublishProcessor.toList().toFlowable());

                // This is to trigger the mStringPublishProcessor on constant intervals
                Observable.interval(0,5,TimeUnit.SECONDS)
                        .map(aLong -> {
                            Timber.d("value emitted: ");  // this log is showing as expected
                            mStringPublishProcessor.onNext("Value "+aLong);
                            return aLong;
                        }).subscribe();
            }

            public LiveData<List<String>> getListLiveData() {
                return mListLiveData;
            }
        }

现在,在我的活动中,我只能看到Observable.interval

中的日志
     com.example.app D/MyActivity$MyViewModel: value emitted: 
     com.example.app D/MyActivity$MyViewModel: value emitted: 
     com.example.app D/MyActivity$MyViewModel: value emitted: 
     com.example.app D/MyActivity$MyViewModel: value emitted: 
     com.example.app D/MyActivity$MyViewModel: value emitted: 
     com.example.app D/MyActivity$MyViewModel: value emitted: 

为什么LiveData观察者从未从Flowable接收任何值?

根据LiveDataReactiveStreams.fromPublisher的文档

  

从ReactiveStreams发布者创建一个Observable流。        当LiveData变为活动状态时,它将订阅发布者的发射。

1 个答案:

答案 0 :(得分:1)

.toList()仅在onComplete()调用之后才会映射收益。在您的示例中,从未调用完成。