Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a preferred type for an Observable with no need for a value in Next events?

Tags:

I have an Observable which is only used for triggering flatMap/map. So I only ever need the Next event and never a value. I could use my own concept for such a trash value, but I'm wondering if there's an RxSwift convention for it.

Here's what I'm dealing with:

// I'd rather not have an Element type that someone might use let triggeringObservable: Observable<SomeSessionClass>   // ...  triggeringObservable.map { _ -> String in // The actual value is ignored     return SomeLibrary.username() // `username()` is only ready when `triggeringObservable` sends Next } 

In this example, triggeringObservable is rx_observer on some property in the library which will let us know that username() is ready to be called.

like image 331
solidcell Avatar asked Apr 11 '16 19:04

solidcell


People also ask

What is observable in angular stack overflow?

An observable is typically a programming construct that can be "watched" by other parts of the code, called the "observers".

What is an observable in Swift?

Observable-Swift is a Swift library for value observing (via explicit usage of Observable<T> ) and subscribable events (also explicit, using Event<T> ). While it is not exactly "KVO for Swift" (it is explicit, there are no "Keys", ...) it is a catchy name so you can call it that if you want.


2 Answers

You can simply use an Observable<Void> for this purpose. Like so:

   let triggerObservable = Observable<Void>.just()      triggerObservable.subscribeNext() {         debugPrint("received notification!")     }.addDisposableTo(disposeBag) 

or in your example:

let triggeringObservable: Observable<Void>   // ...  triggeringObservable.map { Void -> String in // The actual value is ignored    return SomeLibrary.username()  } 
like image 73
Greg Ferreri Avatar answered Sep 20 '22 15:09

Greg Ferreri


In Swift 4 (and probably earlier) you can pass an empty tuple as an argument to a method expecting a Void associated type.

var triggerObservable = PublishSubject<Void>() ... triggerObservable.onNext(()) // "()" empty tuple is accepted for a Void argument 

Or you can define an extension to overload onNext() with no args for the Void case:

extension ObserverType where E == Void {     public func onNext() {         onNext(())     } }  ... triggerObservable.onNext() 
like image 43
Pat Niemeyer Avatar answered Sep 16 '22 15:09

Pat Niemeyer