Coder Social home page Coder Social logo

reactivex / rxswift Goto Github PK

View Code? Open in Web Editor NEW
24.2K 541.0 4.2K 93.58 MB

Reactive Programming in Swift

License: MIT License

Swift 93.92% Ruby 0.27% Shell 0.64% Objective-C 5.18%
swift reactivex reactive ios unidirectional observer functional rxswift

rxswift's Introduction

RxSwift Logo
Build Status Supported Platforms: iOS, macOS, tvOS, watchOS & Linux

Rx is a generic abstraction of computation expressed through Observable<Element> interface, which lets you broadcast and subscribe to values and other events from an Observable stream.

RxSwift is the Swift-specific implementation of the Reactive Extensions standard.

RxSwift Observable Example of a price constantly changing and updating the app's UI

While this version aims to stay true to the original spirit and naming conventions of Rx, this project also aims to provide a true Swift-first API for Rx APIs.

Cross platform documentation can be found on ReactiveX.io.

Like other Rx implementations, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of Observable objects and a suite of methods to transform and compose these pieces of asynchronous work.

KVO observation, async operations, UI Events and other streams of data are all unified under abstraction of sequence. This is the reason why Rx is so simple, elegant and powerful.

I came here because I want to ...

... understand
... install
... hack around
... interact
... compare
... understand the structure

RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more.

It comprises five separate components depending on each other in the following way:

┌──────────────┐    ┌──────────────┐
│   RxCocoa    ├────▶   RxRelay    │
└───────┬──────┘    └──────┬───────┘
        │                  │        
┌───────▼──────────────────▼───────┐
│             RxSwift              │
└───────▲──────────────────▲───────┘
        │                  │        
┌───────┴──────┐    ┌──────┴───────┐
│    RxTest    │    │  RxBlocking  │
└──────────────┘    └──────────────┘
  • RxSwift: The core of RxSwift, providing the Rx standard as (mostly) defined by ReactiveX. It has no other dependencies.
  • RxCocoa: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both RxSwift and RxRelay.
  • RxRelay: Provides PublishRelay, BehaviorRelay and ReplayRelay, three simple wrappers around Subjects. It depends on RxSwift.
  • RxTest and RxBlocking: Provides testing capabilities for Rx-based systems. It depends on RxSwift.

Usage

Here's an example In Action
Define search for GitHub repositories ...
let searchResults = searchBar.rx.text.orEmpty
    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
    .distinctUntilChanged()
    .flatMapLatest { query -> Observable<[Repository]> in
        if query.isEmpty {
            return .just([])
        }
        return searchGitHub(query)
            .catchAndReturn([])
    }
    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
searchResults
    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
        (index, repository: Repository, cell) in
        cell.textLabel?.text = repository.name
        cell.detailTextLabel?.text = repository.url
    }
    .disposed(by: disposeBag)

Installation

RxSwift doesn't contain any external dependencies.

These are currently the supported installation options:

Manual

Open Rx.xcworkspace, choose RxExample and hit run. This method will build everything and run the sample app

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
    pod 'RxSwift', '6.7.0'
    pod 'RxCocoa', '6.7.0'
end

# RxTest and RxBlocking make the most sense in the context of unit/integration tests
target 'YOUR_TESTING_TARGET' do
    pod 'RxBlocking', '6.7.0'
    pod 'RxTest', '6.7.0'
end

Replace YOUR_TARGET_NAME and then, in the Podfile directory, type:

$ pod install

XCFrameworks

Each release starting with RxSwift 6 includes *.xcframework framework binaries.

Simply drag the needed framework binaries to your Frameworks, Libraries, and Embedded Content section under your target's General tab.

XCFrameworks instructions

Tip

You may verify the identity of the binaries by comparing against the following fingerprint in Xcode 15+:

BD 80 2E 79 4C 8A BD DA 4C 3F 5D 92 B3 E4 C4 FB FA E4 73 44 10 B9 AD 73 44 2E F1 CE B0 27 61 40

XCFrameworks Signature Fingerprint in Xcode 15+

Add this to Cartfile

github "ReactiveX/RxSwift" "6.7.0"
$ carthage update

Carthage as a Static Library

Carthage defaults to building RxSwift as a Dynamic Library.

If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage:

carthage update RxSwift --platform iOS --no-build
sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj
carthage build RxSwift --platform iOS

Note: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've filed a bug (SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found here.

Create a Package.swift file.

// swift-tools-version:5.0

import PackageDescription

let package = Package(
  name: "RxProject",
  dependencies: [
    .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0"))
  ],
  targets: [
    .target(name: "RxProject", dependencies: ["RxSwift", .product(name: "RxCocoa", package: "RxSwift")]),
  ]
)
$ swift build

To build or test a module with RxTest dependency, set TEST=1.

$ TEST=1 swift test

Manually using git submodules

  • Add RxSwift as a submodule
$ git submodule add [email protected]:ReactiveX/RxSwift.git
  • Drag Rx.xcodeproj into Project Navigator
  • Go to Project > Targets > Build Phases > Link Binary With Libraries, click + and select RxSwift, RxCocoa and RxRelay targets

References

rxswift's People

Contributors

andrewsb avatar beeth0ven avatar bontojr avatar carlosypunto avatar devxoul avatar diogot avatar fpillet avatar freak4pc avatar hagmas avatar ikesyo avatar kitasuke avatar kzaher avatar lucianopalmeida avatar m0rtymerr avatar mohsenr avatar nanoxd avatar orta avatar pietrocaselani avatar scotteg avatar sergdort avatar sgleadow avatar solidcell avatar stack avatar tarunon avatar thanegill avatar victorg1991 avatar vodovozovge avatar yoshinorisano avatar yury avatar yuzushioh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rxswift's Issues

Problem with rx_subscribeRowsToCellWithIdentifier

func rx_subscribeRowsToCellWithIdentifier<E, Cell where E : AnyObject, Cell: UITableViewCell> (cellIdentifier: String, configureCell: (UITableView, NSIndexPath, E, Cell) -> Void) (source: Observable<[E]>) -> Disposable

I want to be able to configure my cells with structs, but since E must be an AnyObject I can't. Can that be changed to any?

Incorrect observeOn main scheduler behaviour during unsubscribing

observeOn operator seems to prematurely disconnect the observation pipeline during unsubscribing. To illustrate, let's start with a simple example:

let sequence: Observable<String> = create { obs in 
    return AnonymousDisposable { obs.on(.Completed) }
}

let subscription = sequence 
    >- subscribeCompleted { println("COMPLETED") }

subscription.dispose()

The output of the above shows "COMPLETED", which is the expected behaviour. However this is not the case if we observe the same sequence on the main scheduler:

let sequence: Observable<String> = create { obs in 
    return AnonymousDisposable { obs.on(.Completed) }
}

let subscription = sequence 
    >- observeOn(MainScheduler.shareInstance)
    >- subscribeCompleted { println("COMPLETED") } // does not get invoked

subscription.dispose()

It seems that after subscription.dispose() is called but before the AnonymousDisposable handler is called, the subscription chain is severed, so that the completed event never reaches the observer. I suspect the relevant line is in Producer.swift (line 36) where a CompositeDisposable is created and returned:

let d = CompositeDisposable(sink, subscription)

The order of the disposables passed into the CompositeDisposable may need to be reversed to ensure the custom disposable gets invoked first, but this is just my guess.

Ben

Accessing the last value/current state of a Variable

Do you have any plans to provide a property or method on the Variable class to allow directly accessing the latest value or is there currently a mechanism for doing so? I notice in the tests that you access the latest value as follows:

var latestValue: Int?
let subscription = c >- subscribeNext { next in
latestValue = next
}

I am new to Rx, however it seems it would be useful to supply a latestValue/value property on the Variable to simplify cases in which one desires access to the value without having to subscribe. Even a read only property would prove helpful. The subscription just feels like an extra hoop to jump through. Though I do understand if directly accessing the variable is an undesirable breaking with Rx concepts.

Or does "subscribeNext" always send the latest or "last" value?

Issue with rxError(), in RxCocoa

func rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError {...}

The "NSLocalizedDescriptionKey" could not be retrieved from the error created.

This piece of code:

let resultInfo: [NSObject: AnyObject] = (userInfo as NSObject) as! [NSObject: AnyObject]

you pointed it should be:

let resultInfo: [NSObject: AnyObject] = (**mutableDictionary** as NSObject) as! [NSObject: AnyObject]

Obstacle to learning RxSwift: "No such module 'RxSwift'" in example playgrounds

In order to learn RxSwift by example, I launched Rx.xcworkspace and clicked on Introduction.playground. Line 2 immediately came up with the error: No such module 'RxSwift'. The same happens if I open the playground (or any of the playgrounds in Playgrounds/ObservablesOperators).

Am I missing a step? Is this known to be broken?

Fwiw, this is in Xcode Version 6.4 (6E35b).

Question about where to put reactive code.

I currently have my reactive code in the viewDidLoad method, and I dispose everything in the deinit.

However, I noticed that when I exit my view controller, the deinit is never called. I confirmed that the view controller is not getting reused, and that my memory footprint goes up with every entry/exit of my view controller, but no leaks are detected...

Does anybody know what is going on?

var rx_tap instead of func rx_tap

Currently the library uses code like:
public func rx_text() -> Observable<String> { ... }

What would it take to convince you to use something like the below instead?
public var rx_text: Observable<String> { ... }

Clarify the difference between Functional Reactive Programming and RxSwift

This topic has been something hot for me in the last week, the generale feeling around RxSwift is that this framework is Functional Reactive Programming, which, by definition is not.

I think a clarification somewhere in the documentation would help to wipe the general initial confusion that some newcomers are facing. The big issue I am reading on twitter and some articles about Rx is that the FRP (and the association with RAC) is causing a lot of confusion about terminology: Observable and Observer for RX and Behaviour/Signal and Event for FRP.

I created a PR for this, feedbacks are welcomed.

Project "Preprocessor.xcodeproj" has no shared schemes

Cartfile statement: github "ReactiveX/RxSwift" "rxswift-2.0"
Performing a carthage update --platform mac this error appears: Project "Preprocessor.xcodeproj" has no shared schemes

Opening the .xcworkspace and adding the Shared flag to Preprocessor in the schemes, fixes this issue.

rx_didUpdateLocations crash on background thread.

The following code crash if it runs on background thread with the error:

fatal error: Executing on wrong scheduler.

let manager = CLLocationManager()
if manager.respondsToSelector("requestWhenInUseAuthorization") {
  manager.requestWhenInUseAuthorization()
}

manager.rx_didUpdateLocations >- subscribeNext {  x in
  DDLogDebug("location")
}
manager.startUpdatingLocation()

I understand that installing delegate methods is not thread safe and in the most cases, it's should be not allowed from a background thread, but in the case of CLLocationManager there are many cases that people can access from a background thread and in my opinion it's should be allowed to do that from background thread while using RxSwift.

Public Roadmap

It'd be awesome to have a public roadmap of what RxSwift would need to implement to be considered "done" – we could have a Roadmap.md file in the repo that contains checks using GitHub markdown syntax:

  • Still needs to be done
  • This is implemented

Or

  • Still needs to be done
  • This is implemented

So that if someone wants to contribute, they'll have an idea of where to start.

Anyone have any thoughts?

Removal of the 'rx_' prefix

What I was wondering is if there was a possibility of getting rid of the rx_ prefix. I'm not gonna lie, I think it looks out of place in the Swift world. Thus this is really only of 'cosmetic' nature and not particularly high priority.

Either way, the pros of the rx_ prefix is definitely discoverability and clarity. So a new naming convention would need to be at least similarly discoverable and clear.

I was for example thinking about observable, so rx_text would become observableText. In my opinion, this is clear enough and looks a lot nicer.

Anyways, I just opened this issue to figure out what everyone else thinks about this.
Do you prefer the rx_ prefix? If not, what naming convention would you propose?

combineLatest without resultSelector

Something I liked from ReactiveCocoa 2 was the and operator, which operated on two signals sending NSNumbers wrapping BOOLs. Swift gives us an opportunity to do something safer with the type system.

It would be cool if we had a combineLatest that took two (or whatever) Observable<Bool> (or comparable or whatever) and returned an Observable<(Bool, Bool)>. Something like:

func combineLatest(source1: Observable<Bool>, source2: Observable<Bool>) -> Observable<(Bool, Bool)> {
    return combineLatest(source1, source2, { (a: Bool, b: Bool) -> (Bool, Bool) in
        return (a, b)
    })
}

Then we can also have operators like and and or.

func and(observable: Observable<(Bool, Bool)>) -> Observable<Bool> {
    return observable
        >- map({ (thing) -> Bool in
            return thing.0 && thing.1
        })
}

Which lets developers write code like this:

combineLatest(emailIsValid, passwordIsValid)
    >- and
    >- signupButton.rx_subscribeEnabledTo
    >- disposeBag.addDisposable

Which would be 👌

Now, this gets kind of crazy since ideally you could have an arbitrary number of bools in your tuple of Bools. We could use an array or set or some other internal data structure – but I think abstracting away the logic of &&ing a bunch of Bools together into an expressive function would be in the spirit of FRP.

Question: Create Observable and corresponding Observer at the same time

I have a class that implements a delegate protocol for a custom DatePicker which gets called whenever the selected date changes.

Now I want to expose the current date as an Observable.

With ReactiveCocoa I created a Signal and Sink in the constructor, exposing the Signal to the outside and keeping the Sink private to publish new values.

The closest I came with RxSwift was creating a PublishSubject which I exposed as Observable and also kept internally to sendNext new values.

Is this the best approach? I would rather just expose a pure Observable, such that clients can not type-cast back to a PublishSubject and start sending values (though this is only a theoretical problem).

tryMap & flatMap operators

ReactiveCocoa has an operator which is called tryMap is not the best name but I think we should have something similar on RxSwift.

On RxJava, the map itself is able to handle any runtime errors and just send an error event in case something throws inside the map operator. That would be the nicest way to have it. And maybe with Swift 2 will be able to.

But for now, how can we approach that?

Another operator that's really, really missing is a flatMap, don't you think?

I guess I could help with that, but I am creating this issue to discuss before.

Unsubscribing and timer

I'm trying to translate to RxSwift an example in the "Intro to Rx" web.(http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html down where it creates a Timer)

This is what I have:

    var ob:Observable<String> = create {
        observer in

        var timer = NSTimer.schedule(repeatInterval: 1.0) { timer in
            sendNext(observer, "value")
            println("timer event \(timer.fireDate)")
        }

        return AnonymousDisposable {
           // timer.invalidate()
        }
    }

    var subscription = ob
        >- subscribeNext {
            e in
            println(e)
    }

    var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
    dispatch_after(dispatchTime, dispatch_get_main_queue(), {
        println("unsubscribe \(subscription)")
        subscription.dispose()
    })

I'm trying to unsubscribe while keeping the timer running (as the example does) and then invalidate the timer in the dispose block (by uncommenting the "timer.invalidate()" line) to demonstrate the use of the disposable for cleaning purposes.

The problem is, with the code as it is, after the 3 seconds passed, the timer is still running (as expected) but the subscription seems to be active as well.

This is what I get:

value
timer event 2015-07-24 07:43:51 +0000
value
timer event 2015-07-24 07:43:52 +0000
value
timer event 2015-07-24 07:43:53 +0000
unsubscribe RxSwift.AnonymousDisposable
value
timer event 2015-07-24 07:43:54 +0000
value
timer event 2015-07-24 07:43:55 +0000

If I invalidate the timer, of course, I stop receiving events, but it seems I'm not unsubscribing for some reason.

steps towards Carthage compatibility

Carthage compatibility available on rxswift-2.0 branch

What needs to be done:

  • merge all targets from multiple *.xcodeproj into a single RxSwift.xcodeproj
  • the only workspace needed is Rx.xcworkspace containing the playgrounds and RxSwift.xcodeproj as a workspace is required for the Playgrounds to access frameworks as of Xcode 7 beta 5

What this achieves:

  • sustained maintainability
  • reduces complexity (no more maintenance of separate branches)
  • better project structure
  • ease of collaboration on the project
  • Carthage users approval
  • happiness

Proof of concept: https://github.com/lfaoro/RxSwiftTest

  • RxSwift
  • RxCocoa
  • RxBlocking

Cartfile github "lfaoro/RxSwiftTest" "master"

closes #40
/cc @kzaher

Consider Adding Continuous Integration

We should consider adding continuous integration from Travis or CircleCI. This would run tests on pull requests to make sure everything is 🍏 before we merge 🎉

Happy to help out with this.

Add UIControl rx_subscribeEnabledTo

Hey!

Preparing my talk for AltConf tomorrow on FRP, and I'm using RxSwift (ssssshhhhhhh don't tell anyone – I want to focus on concepts and ideas instead of "which FRP framework" I use).

Anyway, coming from ReactiveCocoa, there are a few things I've noticed we could add. I'm making implementations for them in the sample code for now, but when I have time, I'll add tests and send a PR for them.

The first one is adding rx_subscribeEnabledTo for UIControl. Something like

emailTextField.rx_text
    >- map { $0.isEmail() }
    >- submitButton.rx_subscribeEnabledTo
    >- disposeBag.addDisposable

Future, RxSwift 2.0, contributing, ...

Hi guys,

I've tried to plan roadmap and sketch it out (also updated roadmap).

It is not set in stone and we have a lot of flexibility.

I'm really excited about some of the planned things, but when will they be available depends largely on the amount of contributions we'll have.

We now have proper CI that tests all supported configurations for both iOS and OSX. We also have UI automation for example app (Carlos is still working on iOS 7 automation). The example apps aren't just examples, they also have some fairly complex Rx code. By ensuring it runs on all supported combinations, we can make sure people will have as few problems as possible.

CI is also important because it was pretty hard to accept contributions from community, but things have improving significantly.

Our full suite CI tests run for about 25 minutes on Travis (without automation tests), and our automations suite ran couple of times longer last time I've checked :)

In case you want to contribute to this project in any way, please let me know, we can open separate issues for your contributions and plan everything.

In that way we can make sure work isn't duplicated and that we are all pulling in the same direction.

So far, we've had some really amazing contributions, and people have really gone far beyond call of duty in a lot of cases. There was really tons of different ways people have contributed, from commits, compiler bug investigations and workarounds, reviewing PRs, sharing positive feedback on social networks...
Thnx a lot guys.

I've received questions about how to best contribute some time ago from @ashfurrow , @bontoJR , @carlosypunto , but because we didn't have infrastructure in place, and I was sprinting for last 3 months to get to this point, I couldn't provide clear directions where does this project need help the most until we've hit this point.

If anyone has time to spare helping this project or ideas where would you like to contribute, I think this is becoming a lot easier now.

Here is the pasted roadmap.

Short-term plans

RxSwift 2.0 version

  • * - refactoring core logic from RxResult to do/throw/catch
  • * - refactoring from using RxBox from Event enum.
  • * - Remove using send* internally and using .on(.Next(element))
  • * - Moving from >- to . (curried functions to protocol extensions, this is attempt #2) - one of the reasons why >- was chosen was to make it future proof, so in case we transition from >- to ., users could just find replace >- with . because of uniqueness of >- operator
  • RxSwift - removing OrDie prefix for functions that fail and just use compiler throws overloads (mapOrDie becomes map)
  • RxSwift - adding lockless versions of operators to power RxUnits project

Porting to Swift 2.0 - Kind of done, but still some open issues there

  • * - rebasing from 1.9 version - I'll probably do that soon
  • RxCocoa - Making RxDataSourceStarterKit compilable with Swift 2.0 compiler
  • RxCocoa - find a way to detect is UICollectionView is in the process of animating changes, and if is, then do reload, otherwise animated update (this creates problems for generic animated updates)

Other

  • RxSwift - Inline documentation for operators first (as been suggested by @orta)
  • RxSwift - optimized just and from operators

Mid-term plans

  • RxUnits - New project build on top of RxSwift that should enable adding Units to observables in similar fashion to units in Physics. It should enable writing entirely lockless code transparently with compile time guarantees of correctness. It would also enable compiler to prove properties about Observables, for example, handling errors before binding to UI and making sure observe happens on UI thread, and make code more readable. It's relation with RxCocoa project is still unsure.
  • RxObjC - New project built on top of RxSwift - Proof of concept is done, but waiting for compiler bugs to be solved :(. Still unsure will ObjC have powerful enough generics so we can do RXObservable<Element>.
  • RxCocoa - Apple watch support - somebody has started to work on that #70, I'm curios what can we do there

Long-term plans

  • RxSwift, RxCocoa - Adding Linux support - looking for somebody with experience with multithreading in Linux
  • RxSomethingUndefined - trying to figure out can we use ReactNative "virtual dom" - at this point I don't know much about this
  • RxSomethingUndefined - figuring out can we do something like http://cycle.js.org/

Swift Compiler Error for iOS 7

I'm trying to build RxSwift and RxCocoa for iOS 7.
As iOS 7 doesn't support dynamic frameworks, I added the .swift, .m, .h files to my project.
(RxSwift, RxCocoa/RxCocoa.h, RxCocoa/Common, RxCocoa/iOS)

project

And run in RxSwift directory

find . -name "*.swift" -exec sed -i '' 's|^import RxSwift||' {} \;

But I see build error for RxCocoa...

buildmessage

Any solution? Thank you.

Doc / Example: Converting callback function to RxSwift

Hi,

when evaluating RxSwift, I was unable to find a practical example to convert a callback-style API to RxSwift.

How would one wrap this with RxSwift for example:

    func add(a: Int64, _ b: Int64, cb: (Int64) -> ()) {
        cb(a+b)
    }

Would for example returning an Observable<Int64> be the best choice, or are there specific options for returning only a single value?

Thanks for your help!

Architecture Error when debuggingin on iPod Touch Device

dyld: Library not loaded: @rpath/RxSwift.framework/RxSwift
      Referenced from: /private/var/mobile/Containers/Bundle/Application/5CF8EAE4-E014-44DE-878F-E5C17DB1B19F/Eden.app/Eden
      Reason: no suitable image found.  Did find:
  /private/var/mobile/Containers/Bundle/Application/5CF8EAE4-E014-44DE-878F-E5C17DB1B19F/Eden.app/Frameworks/RxSwift.framework/RxSwift: mach-o, but wrong architecture
  /private/var/mobile/Containers/Bundle/Application/5CF8EAE4-E014-44DE-878F-E5C17DB1B19F/Eden.app/Frameworks/RxSwift.framework/RxSwift: mach-o, but wrong architecture

So strange... It works completely fine on my iPhone 6 and iPads

UICollectionView rx_contentOffset and UICollectionViewDelegateFlowLayout

When I use rx_contentOffset and have implementation of UICollectionViewDelegateFlowLayout its crashs on :

[RxCocoa.RxCollectionViewDelegateProxy collectionView:layout:sizeForItemAtIndexPath:]: unrecognized selector sent to instance

Should I use also collectionView.rx_setDelegate(self) ?

how to get binding to work?

Hi,

I know this is not an issue, but i wondered why everytime i want to use ">-" error shown in xcode said "Operator is not know binary operator". How to make it work?

i use swift 2.0 , this is my code

leftBarItem.rx_tap
         >- subscribeNext ({ [weak self]  in
                NSLog("Hallo world %@", self!)})

Cannot invoke 'rx_observe' with an argument list of type '(String)'

I have a class that looks like this:

public class MyClass: NSObject {
   public var active: Bool = false
}

Then at some point either on the init or on another function I'm trying to do this:

self.rx_observe("active")

But it doesn't matter what parameters I pass and its labels or not I keep receiving this:

Cannot invoke 'rx_observe' with an argument list of type '(String)'

Any ideas? ¯_(ツ)_/¯

Also if I try to access KVOObservable directly the compiler doesn't seem to find it :/


Edit: This is on the feature/swift2.0 branch

rx_observe can be more intuitive as rx_observe<AnyObject?>

rx_observe for KVO compliant objects is a little confusing

For example. I may want to store my apiToken in

  NSUserDefaults.standardDefaults().setObject(apiToken, forKey: "apiToken")

I should be able to subsequently observe this like so

 NSUserDefaults.standardUserDefaults().rx_observe("apiToken")
        >- subscribeNext{ myApiToken -> Void in
            println(myApiToken)
        } 

However the compiler doesn't understand this syntax.
It would be helpful if rx_observe was generically typed with

  rx_observe<AnyObject?>

Fluent rx names

Having spent from function composition to protocol extension some terms cease to be obvious. Like subscribeTextOf which it is a bit confusing. Now is the time since the 2.0 API is not final.
Open this thread for the native speakers can help to polish some confusing terms.

Exception raised using rx_didChangeAuthorizationStatus

I'm just wrapping my head around the whole Rx thing so apologies if this is something of my own doing.

My viewDidLoad method looks something like this:

  override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.rx_didChangeAuthorizationStatus
      >- subscribeNext() { status in
        println(status)
      }
      >- disposeBag.addDisposable
  }

Upon execution an exception is raised inside the rx_didChangeAuthorizationStatus CLLocationManager extension.

Could not cast value of type '__NSCFNumber' (0x7fe523b6b0b8) to 'C.CLAuthorizationStatus' (0x102105250).

Using swift 1.2 and iOS SDK 8.4

listener on more view controller

is there any way to get the result of subscribe in different view controller/class? for example for login i open a modal on my navigation controller. to start requst i subscribe login on modal view controller. when it finish i can get result on modalviewcontroller. how can i catch the login result on a view controller in navigation controller?

Observe typealiases properties

I wanted to use RxCocoa to observes a views bounds like this:

        let obs : Observable<CGRect?> = nibView.rx_observe("bounds")
        obs >- subscribeNext {
            bounds in
            println(bounds)
        }

But then bounds is always nil.

When I change it to this:

        let obs : Observable<AnyObject?> = nibView.rx_observe("bounds")
        obs >- subscribeNext {
            bounds in
            println(bounds)
        }

bounds is actually an Optional(NSRect: {{0, 0}, {768, 43.5}}).

I can't seems to access the NSRect type in my iOS project (even though I import Foundation), and since it is only a type alias for CGRect, I thought maybe this code should work with CGRect? like in the first snippet?

Thanks for your suggestions.

Strange crash after .rx_observe() usage

So I have an subscription on viewModel.annotations which swaps out the <MKAnnotation>s on the map when the ViewModel's array changes:

    viewModel.annotations >- subscribeNext { [weak self] annotationsArray in
        self?.mapView.removeAnnotations(self?.mapView.annotations)
        self?.mapView.addAnnotations(annotationsArray) // marker1 
    }

This works great, the map is updated when I change that array, it's all good. Except when I add the following:

    let mapViewSignal = self.mapView.rx_observe("annotations") as Observable<[AnyObject]?>
    mapViewSignal >- subscribeNext { x in
        println("annotations did change")
    }

With this present, the code at marker1 now crashes (where before it worked great) with error:

[Swift._SwiftDeferredNSArray intersectsSet:]: unrecognized selector sent to instance 0x7f9c4a73d500

I've no idea what could cause this - why is it now calling a NSSet method on my array? And why does this only happen when I add a KVO observer (self.mapView.rx_observe("annotations")) to MKMapView?

Any help here gladly received! :)

p.s. loving RxSwift so far! The documentation is way more clear than I've found ReactiveCocoa's to be.

I miss more documentation

Good job, I'm really happy with this library, I like much more than RAC 3.0. I am new to the FRP world and I miss some more documentation and simplest example.The GitHubSignup example is quite clear but WikipediaImageSearch see it a little complicated.
I miss documentation in the code.

We are migrating towards RxSwift 2.0 version and Swift 2.0 compiler

I’ve made a branch called rxswift-1.0 for anyone who is using RxSwift-1.* version.
I’ll merge today rxswift-2.0 into develop, and master branches and release RxSwift2.0-alpha.1

Don't worry, we will be applying critical hotfixes to 1.9 version, but since the entire ecosystem is migrating towards Swift 2.0, we will be focusing on adding new features only to RxSwift 2.0 version.

Use a real CHANGELOG?

It's nice that you're using GitHub's releases feature, but nothing beats actually including a CHANGLOG so that you can easily look over the changes from the terminal.

Is it really necessary to have RxBlocking as a 3rd framework?

RxBlocking contains only 1 file with an RxSwift dependency and ~150 lines of code. Is it really necessary to have it as a separate framework?

I believe the goal is to make sure Rx users don't use blocking in their code and link RxBlocking just to their test target but I'm wondering...

Is it really worth it to increase the complexity of the framework instead of just displaying a warning to the users on ⌥-click?

Carthage Support?

Hey,

I see a reference to Carthage in the .gitignore, but simply adding to a Cart file produces the error

*** Fetching RxSwift
*** Checking out RxSwift at "1.6"
*** xcodebuild output can be found in /var/folders/1w/kkmgrb0n1p7gm08j06x8wjtw0000gn/T/carthage-     xcodebuild.kBvFvj.log
Project "Preprocessor.xcodeproj" has no shared schemes

Is the project expected to support Carthage?
More than happy to take a swing at it if not.

Swift 2.0

Hi guys,

I'm currently working on RxCocoa refactorings, and currently don't have time to play with Swift 2.0 :(
The earliest that will be on my plate is in a week or two, don't think I'll manage to do it before that time.

Since there is some community interest in using RxSwift with Swift 2.0, I've created a branch where you can share your changes if somebody has managed to make it to work with new version of Swift, so others don't have to redo that work.

That's best I can do so far.

Kruno

post request

how can i do rest post request? thank you

i'm new in rx

if:then:else operator: missing?

Hey,

Is there a RxSwift analog for the ReactiveCocoa if:then:else operator?

Returns a signal which passes through nexts and errors from trueSignal and/or falseSignal, and sends completed when both boolSignal and the last switched signal complete

http://cocoadocs.org/docsets/ReactiveCocoa/2.3.1/Classes/RACSignal.html#//api/name/if:then:else:

It seems some other reactiveX implementations have an ifThen operator, but I can't find it here.

If not, please could someone point me to a way to do the following:

-I have a signal 'A' which I want to only pass values if another signal 'B' currently evaluates to 'true' somehow. takeWhile etc complete once the predicate matches true, but I don't want this - I want to have fine-grained control over signal A via signal B. filter doesn't feel right here, because it would need to reach outside its own context to some external state, which wouldn't be very functional :)

Thanks for all advice in advance!
Ian

UITableView+Rx rework.

I would like to see the UITableView extension reworked a bit. I envision having the class subscribe to an observable array and have the ability to add and remove individual cells when the array changes.

The code for finding the add/remove/moves is available here (http://www.swift-studies.com/blog/2015/5/15/swift-coding-challenge-incremental-updates-to-views).

And yes, I tried his challenge. I managed to make a function that was almost as fast, but is was essentially the same structure as his solution so I gave it up.

I'll try making this enhancement myself, but I'm not strong on this RX stuff yet so if someone else wants to take up the gauntlet...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.