reactivex / rxswift Goto Github PK
View Code? Open in Web Editor NEWReactive Programming in Swift
License: MIT License
Reactive Programming in Swift
License: MIT License
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.
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
how can i do rest post request? thank you
i'm new in rx
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
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).
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:
Or
So that if someone wants to contribute, they'll have an idea of where to start.
Anyone have any thoughts?
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?
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.
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).
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?
rxswift-2.0
branchWhat needs to be done:
*.xcodeproj
into a single RxSwift.xcodeproj
Rx.xcworkspace
containing the playgrounds and RxSwift.xcodeproj as a workspace is required for the Playgrounds to access frameworks as of Xcode 7 beta 5What this achieves:
Proof of concept: https://github.com/lfaoro/RxSwiftTest
Cartfile
github "lfaoro/RxSwiftTest" "master"
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
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.
Can you use https://github.com/robrix/Box?
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?
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.
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.
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...
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
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
?
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]
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> { ... }
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.
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.
class SkipUntil<Element, Other>: Producer<Element>
is missing.
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
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.
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
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) ?
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)
And run in RxSwift directory
find . -name "*.swift" -exec sed -i '' 's|^import RxSwift||' {} \;
But I see build error for RxCocoa...
Any solution? Thank you.
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?
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
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.
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.
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!
Something I liked from ReactiveCocoa 2 was the and
operator, which operated on two signals sending NSNumber
s wrapping BOOL
s. 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 Bool
s. 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 Bool
s together into an expressive function would be in the spirit of FRP.
Any known issue? Thanks.
I can't find an answer in readme.md and google.
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.
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!)})
On RxExample-IOS writing text on search field of 'Search Wikipedia' launch exception "attempted to retain deallocated object".
I'm using Xcode 6.4 not 6.3.
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.
RxResult
to do
/throw
/catch
RxBox
from Event
enum.send*
internally and using .on(.Next(element))
>-
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 >-
operatorOrDie
prefix for functions that fail and just use compiler throws
overloads (mapOrDie
becomes map
)RxUnits
projectRxDataSourceStarterKit
compilable with Swift 2.0 compilerjust
and from
operatorsUnits
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 Observable
s, 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.RXObservable<Element>
.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?>
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?
I just wondering how far we can push the lib to. And I mean runtime performance for RxSwift vs handwriting error prone code. :)
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.
This isn't an instantly actionable, but ideally it's going to be good to start pushing this 1% publicly documented upwards.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.