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

13,215

Solution 1

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() 
}

Solution 2

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()

Solution 3

This worked for me on Swift 4.1:

Observable<Void>.just(Void())

Solution 4

This worked for me on Swift 4.2:

Observable<Void>.just(())
Share:
13,215

Related videos on Youtube

solidcell
Author by

solidcell

Professional software engineer since 2010. Hooked on iOS since 2014.

Updated on June 07, 2020

Comments

  • solidcell
    solidcell almost 4 years

    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.

  • Womble
    Womble about 4 years
    In Swift 5.1, I had to explicitly pass a Void() to onNext(). Cheers.
  • Martin Berger
    Martin Berger over 3 years
    Your solution enables multiple events with one subsrciption. The ones with Just are single use only. +1