How to create an Observable from OnClick Event Android?

后端 未结 5 1241
忘掉有多难
忘掉有多难 2020-12-07 17:10

I\'m new in reactive programming. So I have problem when create a stream from an Event, like onClick, ontouch...

Can anyone help me solve this problem.

Thank

5条回答
  •  北海茫月
    2020-12-07 17:28

    You could use a Subject.

    A Subject is a sort of bridge or proxy that acts both as an Subscriber and as an Observable. Because it is a Subscriber, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.

    public class Events {
        public static PublishSubject  myEvent = PublishSubject.create ();
    }
    
    
    

    When you want to publish something

    Events.myEvent.onNext(myObject);
    

    When you want to receive an event

    Events.myEvent.subscribe (...);
    

    Edit

    **Using Architecture Components LiveData is better because it handles the lifecycle of and activity or fragment and you don't have to worried about unsubscribe from events because it observe the ui components lifecycle.

    MutableLiveData event = new MutableLiveData<>();
    
    
    

    when you want to publish something

    event.postValue(myObject);
    

    When you want to receive and event

    event.observe(lifeCycleOwner, (myObject)->...);
    

    提交回复
    热议问题