Android 使用RxBus将对象传输到片段

Android 使用RxBus将对象传输到片段,android,rx-java2,Android,Rx Java2,我正在努力实现RxBus。我计划用它在片段/活动/对话框之间移动对象动物。在上面的代码中,我尝试将我的对象从对话框窗口移动到属于QuestionActivity的AnswerFragment。我知道我可以不用RxBus,但这是原则上的 RxBus public class RxBus { private static RxBus instance; private PublishSubject<Animal> animal = PublishSubject.crea

我正在努力实现RxBus。我计划用它在片段/活动/对话框之间移动对象
动物
。在上面的代码中,我尝试将我的对象从对话框窗口移动到属于
QuestionActivity
AnswerFragment
。我知道我可以不用RxBus,但这是原则上的

RxBus

public class RxBus {
    private static RxBus instance;

    private PublishSubject<Animal> animal = PublishSubject.create();

    public static RxBus instanceOf() {
        if (instance == null) {
            instance = new RxBus();
        }
        return instance;
    }


    public void setAnimal(Animal sendedAnimal) {
        animal.onNext(sendedAnimal);
    }

    public Observable<Animal> getAnimal() {
        return animal;
    }
}
并尝试在
回答片段
上捕捉我的
动物

 ...
 private Animal currentAnimal;
 ...
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_question_answer, container, false);

        Disposable disposable = RxBus.instanceOf().getAnimal().subscribe(animal -> currentAnimal = animal);
        disposable.dispose();
但我的动物是空的,我不知道为什么。直觉上,我认为这与生命周期有关。我想当我写作的时候

RxBus.instanceOf().setAnimal(animal);

…我的
AnswerFragment
还没有活的,所以
AnswerFragment
不能从RxBus带走动物,当
AnswerFragment
消失时,这个物体可能已经消失了。我说的对吗?如果是,我该怎么办?

使用行为主体或重播主体,因为这些主体提供以前发出的值。PublishSubject将只向订阅者提供订阅点之后发出的值。

请注意,
iv.setOnClickListener(v->{
不必运行来显示
AnswerFragment
,这就是为什么他们通常告诉您使用
片段.setArguments()
RxBus.instanceOf().setAnimal(animal);