Has anyone tried exposing a function to Swift for ...
# reaktive
s
Has anyone tried exposing a function to Swift for creating an observable without losing generics?
a
Could you please provide an example of a function with losing generics?
s
Let me try recalling. I tried creating one but it didn’t work so I threw away my code 😄. IIRC the problem was that the generic type of my lambda function parameter was getting lost after conversion to obj-c.
IntelliJ’s local history doesn’t seem to have anything either. I’ll retry writing it, but I’m interested if you already have a working gist @Arkadii Ivanov?
a
The thing is I don't understand what you are trying to achieve 🙂 What sort of function you are trying to create? Would be good to see an example of API.
s
I am trying to expose reaktive’s
observable{}
for creating a new Observable from Swift. I think my 2nd attempt seems to have worked. I’m able to use this from Swift:
Copy code
class ObservableCreator<T : Any>(
  val onSubscribe: (ObservableEmitterWrapper<T>) -> Unit
) {
  fun toReaktive(): Observable<T> {
    return observable { emitter ->
      onSubscribe(ObservableEmitterWrapper(emitter).freeze())
    }
  }
}

class ObservableEmitterWrapper<T : Any>(val emitter: ObservableEmitter<T>) {
  fun onNext(value: T) = emitter.onNext(value)
  fun onError(error: Throwable) = emitter.onError(error)
  fun onComplete() = emitter.onComplete()
  fun setCancellable(cancellable: () -> Unit) = emitter.setCancellable(cancellable)
}
what do you think?
a
Now I got it. Yeah, Obj-C supports generics only for classes. So your approach should work.
Btw your emitter wrapper can look like this:
Copy code
class ObservableEmitterWrapper<in T : Any>(emitter: ObservableEmitter<T>) : ObservableEmitter<T> by emitter
s
ye ye ye delegates ftw! thank you!