我显示一个DialogFragment
并在后台加载数据。我希望对话框显示出来,数据继续加载并逐步更新已经可见的对话框。
问题
在可观察对象完成之前,不会显示该对话框。为什么?
码
private final static Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Observable<List<Data>> observable = Observable.create(new Observable.OnSubscribe<Data>()
{
@Override
public void call(Subscriber<? super Data> subscriber)
{
// iterate and create data
for (int i = resolveInfo.size() - 1; i >= 0; i--)
{
Data d = ...;
subscriber.onNext(d);
}
subscriber.onCompleted();
}
})
.onBackpressureBuffer()
.buffer(150, TimeUnit.MILLISECONDS)
.filter(new Func1<List<Data>, Boolean>()
{
@Override
public Boolean call(List<Data> rxSingleDatas)
{
return rxSingleDatas.size() > 0; // only deliver not emtpy lists!
}
})
.onBackpressureBuffer()
.doOnNext(new Action1<List<Data>>()
{
@Override
public void call(List<Data> shareDatas)
{
// add result to list + notify adapter
for (int i = 0; i < shareDatas.size(); i++)
mData.add(shareData);
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
}
})
.doOnCompleted(new Action0()
{
@Override
public void call()
{
// flag to indicate all data is loaded
mReady = true;
}
});
// subscribe on handler thread for async execution
// observe on main thread for updating UI
mSubscription = observable
.subscribeOn(HandlerScheduler.from(mHandler))
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}
@Override
public void onDestroy()
{
if (mSubscription != null)
mSubscription.unsubscribe();
super.onDestroy();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity())
.title(R.string.share_with)
.cancelable(true)
.autoDismiss(false);
mAdapter = ...;
builder
.adapter(mAdapter, new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) {
if (!mReady)
return;
// handle click
}
});
MaterialDialog dlg = builder.build();
return dlg;
}
编辑
我将处理程序替换为在后台线程上运行的处理程序,但这导致以下执行:
CalledFromWrongThreadException
当尝试在doOnNext
调用中更新适配器时...我会说observeOn
应该具有以下效果: doOnNext
在主线程上被调用,但是似乎这不起作用... 最佳答案
关于subscribeOn
和observeOn
运算符的工作方式有些困惑。subscribeOn()
将该线程应用于生成部分(此处为Observable.create()
),然后再进行处理,直到第一个observeOn()
或按设计对特定线程进行操作的运算符为止。因此,observeOn
切换线程以在链中对其下游进行操作。除非明确告知,否则RxJava不会自动切换线程。