我们如何在 RxJava
链中链接对话 fragment 并等待其结果(单击哪个按钮)。
类似于:
buttonClickObservable.flatMap(v -> showDialogAndWaitForResponse()).subscribe(dialogResult -> doSomething());
这可能吗?请有人指导我。
谢谢。
最佳答案
如果您正在使用 RxBinding
库,您可以这样做:
buttonClickObservable
.doOnNext(e -> showDialog())
.flatMap(v -> dialogBtnClickObservable)
.subscribe(clicked -> Log.d("TAG", "It's working!"));
编辑: 好的,事实证明使用 RxBinding 观察对话框的 View 并不是那么容易。所以,这是一个使用 RxBinding
和 PublishSubject
public class MainActivity extends AppCompatActivity {
Button btn;
//here you can declare the Subject with the type
//you're expecting as a result from the dialog
public static final Subject<String> fragmentResultSubject = PublishSubject.create();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
RxView.clicks(btn)
.doOnNext(e -> showDialog())
.flatMap(v -> fragmentResultSubject)
.subscribe(fragmentResult -> Log.d("TAG", fragmentResult));
}
private MyDialogFragment showDialog() {
MyDialogFragment myDialogFragment = new MyDialogFragment();
myDialogFragment.show(getSupportFragmentManager(), "FRAG_TAG");
return myDialogFragment;
}
public static class MyDialogFragment extends DialogFragment {
Button dialogBtn;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dialog, container, false);
dialogBtn = rootView.findViewById(R.id.dialogBtn);
dialogBtn.setOnClickListener(v -> fragmentResultSubject.onNext("Fragment btn clicked"));
return rootView;
}
}
}
关于android - 在 RxJava 中链接对话 fragment 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48902782/