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

LiveDataReactiveStreams: converting Flowable to LiveData doesn't work

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

Activity

    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);
                    }
                }
            });

        }
    }

视图模型class

     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;
            }
        }

现在,在我的 activity 中,我只能看到来自 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

的文档

Creates an Observable stream from a ReactiveStreams publisher. When the LiveData becomes active, it subscribes to the emissions from the Publisher.

.toList() 将仅在 onComplete() 调用后映射 return。在您的示例中,永远不会调用完成。