How to keep subscriber after onError(RxJava) - retrofit

1st, I tried
// used retrofit
public interface ApiService {
#GET(/get_some_data)
Observable<SomeData> getSomeData();
}
// clickStream created by onClick event
// No.1
clickStream
.flatMap(e -> apiService.getSomeData())
.subscribe(
success -> Log.d("tag", "success"),
error -> Log.d("tag", "error"),
() -> Log.d("tag", "complete"))
this is fine if getSomeData() is success.
I can get some data each click.
but if occur error, unsubscribed.
(so click is not works after error)
2nd, I tried below.(with onErrorResumeNext) but unsubscribed.
(didn't call onError, but called onComplete. so unsubscribed)
// No.2
clickStream
.flatMap(e -> apiService.getSomeData())
.onErrorResumeNext(throwable -> Observable.empty()) // add this line
.subscribe(
success -> Log.d("tag", "success"),
error -> Log.d("tag", "error"),
() -> Log.d("tag", "complete"))
3rd, I tried below.(with retry)
// No.3
clickStream
.flatMap(e -> apiService.getSomeData())
.retry(5) // add this line
.subscribe(
success -> Log.d("tag", "success"),
error -> Log.d("tag", "error"),
() -> Log.d("tag", "complete"))
this is better than No.1. but unscribed.
I want to make refresh button that works after error.
I want to know
Can I keep or re-subscribe subscriber?
Is this a proper way in Rxjava?
sorry for my poor English.

Your Nr. 2 was quite close - try this:
clickStream
.flatMap(e -> apiService.getSomeData()
.onErrorResumeNext(throwable -> Observable.empty())) // add this line
.subscribe(
success -> Log.d("tag", "success"),
error -> Log.d("tag", "error"),
() -> Log.d("tag", "complete"))
Notice that I just moved one closing parenthesis so that the onErrorResumeNext is now called after every error and is part of the "inner" Observable.

Related

perform network call and proceed - asynchronous task

i just started learning Swift a year ago, so please be patient with me :)
i am downloading JSON data with a network call, and as soon as i successfully received those rows, i then continue to clear the rows inside my coreData entity, and rewrite those new rows into coredata..
i am having a hard time understanding this asynchronous procedure..
what i've learned is that i have to use completion handlers, but i still can't use it the way i need to.. especialy when i need to proceed after those 3 steps were executed..
First call from button action:
#IBAction func updateButtonPressed(_ sender: Any) {
self.myCoreData.update() {(success) in // calls my update method
print(success!)
textField.text = success! // not possible bc not in the Mainthread
}
textField.text = "blabla" // gets executed before the result is available
methods:
func update(completion: #escaping (String?) -> Void) { //parent method which calls sub methods
var returnValue = ""
Step1getJson {_ in. // step 1
self.Step2Delete { // step 2
self.Step3Save { // step 3
returnValue = "return Value: \(self.step1Result)"
completion(returnValue)
}
}
}
}
func Step1getJson(completion: #escaping (Bool) -> ()) {
var success = false
if let url = URL(string: "https:foo") {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
do {
let parsedJSON = try JSONDecoder().decode([RemoteWire].self, from: data)
print("-- Successfully received \(parsedJSON.count) datarows ")
self.JSON = parsedJSON
self.step1Result = "-- Successfully received \(parsedJSON.count) datarows "
success = true
} catch {
print(error)
}
completion(success)
}.resume()
}
}
func Step2Delete(completion: () -> Void) {
...delete entity rows
completion()
}
func Step3Save(completion: () -> Void) {
.. save new JSON rows to coreData
completion()
}
Everything is working fine that far, and step 2 and step 3 get successfully called when network download has finished..
but how can i proceed after those steps were executed inside my updateButtonPressed function?
if i try to write those results into any UI element inside my completion block, a textField or whatever, i get an error that this has to happen in the main thread, and if i execute it outside the completion block those lines get executed far too early, when no results are available yet.
i feel like i have understanding problem with this, i hope you guys can help me out and guide me in the right direction.
As swift allows any changes or updates in UI element only from main thread, you need to call the main thread to update the UI.
Replace the below code
#IBAction func updateButtonPressed(_ sender: Any) {
self.myCoreData.update() {(success) in // calls my update method
print(success!)
textField.text = success! // not possible bc not in the Mainthread
}
}
with the new code
#IBAction func updateButtonPressed(_ sender: Any) {
self.myCoreData.update() {(success) in // calls my update method
print(success!)
DispatchQueue.main.async {
textField.text = success! // Now possible because it is in main thread
}
}
}

Background data task in watchOS

I'm trying to build a basic proof-of-concept watchOS app and complication that pulls JSON data from an API and displays a gauge based on that.
I've watched Apple's 'Keping your watch app up to date' and found several other questions on the subject but the sample code has been taken down.
The API provides forecasts for the next ~48 hours and can be used to populate the timeline entries for the complication. When the Complication Controller requests the timeline entries I pull the data from the Extension Delegate and therefore it must be kept up to date. However the process of scheduling background data tasks has got me stumped. When I call backgroundSession.dataTask(with: URL(string: "https://...... I expect my URLSessionDataDelegate functions to be called but they never are and I never get a the handle(_ backgroundTasks) called with WKURLSessionRefreshBackgroundTask
Question:
When a WKApplicationRefreshBackgroundTask is sent to my ExtensionDelegate how should I request/schedule data from the API and then receive it?
Code
//ExtensionDelegate
class ExtensionDelegate: NSObject, WKExtensionDelegate, URLSessionDelegate, URLSessionDataDelegate {
...
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task in backgroundTasks {
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
print("background task as WKApplicationRefreshBackgroundTask")
self.scheduleURLSession()
backgroundTask.setTaskCompletedWithSnapshot(false)
return
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
print("background task as WKURLSessionRefreshBackgroundTask")
let backgroundConfigObject =
URLSessionConfiguration.background(withIdentifier: urlSessionTask.sessionIdentifier)
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
print("Rejoining session ", backgroundSession)
self.savedTask = urlSessionTask
return
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
func scheduleURLSession() {
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "nz.co.craigstanton")
backgroundConfigObject.sessionSendsLaunchEvents = true
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
let dataTask = backgroundSession.dataTask(with: URL(string: "https://craigstanton.co.nz/uvi-test?latitude=-36&longitude=174")!)
print("scheduleURLSession about to 'resume' ")
dataTask.resume()
}
//Delegate callbacks
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("Data task error", error)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
completionHandler: #escaping (URLSession.ResponseDisposition) -> Void) {
print("urlSession Delegate did receive everything ")
}
func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("urlSession Delegate did receive something ")
}

f# async cancel not working - stuck on console.readline

I am running a simple chat app with f#. In the chat when one user types "exit" then I want both clients to finish the chat. Currently I am running in the console, and so read and write are blocking, but I am using a class to wrap the console so there is no async problems.
(In the following code the sendUI and reciveUI are async functions that send and recieve messages over the wire)
type IConnection =
abstract Send : string -> Async<bool>
abstract Recieve : unit -> Async<string>
abstract Connected : bool
abstract Close : unit -> unit
type IOutput =
abstract ClearLine : unit -> unit
abstract ReadLine : ?erase:bool -> string
abstract WriteLine : string -> unit
let sendUI (outputer:#IOutput) (tcpConn: #IConnection) () =
async {
if not tcpConn.Connected then return false
else
let message = outputer.ReadLine(true)
try
match message with
| "exit" -> do! tcpConn.Send "exit" |> Async.Ignore
return false
| _ -> if message.Trim() <> ""
then do! message.Trim() |> tcpConn.Send |> Async.Ignore
outputer.WriteLine("me: " + message)
return true
with
| e -> outputer.WriteLine("log: " + e.Message)
return false
}
let recieveUI (outputer:#IOutput) (tcpConn: #IConnection) () =
async {
if not tcpConn.Connected then return false
else
try
let! response = tcpConn.Recieve()
match response with
| "exit" -> return false
| _ -> outputer.WriteLine("other: " + response)
return true
with
| e -> outputer.WriteLine("error: " + e.Message)
return false
}
let rec loop (cancel:CancellationTokenSource) f =
async {
match! f() with
| false -> cancel.Cancel(true)
| true -> do! loop cancel f
}
let messaging recieve send (outputer: #IOutput) (tcpConn:#IConnection) =
printfn "write: exit to exit"
use cancelSrc = new CancellationTokenSource()
let task =
[ recieve outputer tcpConn
send outputer tcpConn ]
|> List.map (loop cancelSrc)
|> Async.Parallel
|> Async.Ignore
try
Async.RunSynchronously (computation=task, cancellationToken=cancelSrc.Token)
with
| :? OperationCanceledException ->
tcpConn.Close()
let exampleReceive =
{ new IConnection with
member this.Connected = true
member this.Recieve() = async { do! Async.Sleep 1000
return "exit" }
member this.Send(arg1) = async { return true }
member this.Close() = ()
}
let exampleOutputer =
{ new IOutput with
member this.ClearLine() = raise (System.NotImplementedException())
member this.ReadLine(erase) = Console.ReadLine()
member this.WriteLine(arg) = Console.WriteLine(arg) }
[<EntryPoint>]
let main args =
messaging recieveUI sendUI exampleOutputer exampleReceive
0
(I wrapped the console with an object so i wont get weird things on screen: outputer)
When I get "exit" over the wire i return false and so the loop calls cancel so it should also stop the sending messages async computation.
However, when I do this, the sendUI gets stuck:
async {
//do stuff
let message = Console.ReadLine() //BLOCKS! doesn't cancel
//do stuff
}
One fix would be to somehow make Console.ReadLine() an async, however the simple async { return ...} does not work.
I also tried running it as a task and calling Async.AwaitTask, but this does not work either!
I read that one can use Async.FromContinuations but I couldn't figure out how to use it (and what I tried didn't solve it...)
Little help?
EDIT
The reason this doesn't simply work is because the way async computations cancellation work. They check whether to cancel when it reaches a let!/do!/return! etc, and so the solutions above do not work.
EDIT 2
Added runnable code sample
You can wrap the Console.ReadLine in its own async, then call that with Async.RunSynchronously and a CancellationToken. This will allow you to cancel that blocking operation, because it won't be on the same thread as the console itself.
open System
open System.Threading
type ITcpConnection =
abstract member Send: string -> unit
let readLineAsync cancellation =
async {
try
return Some <| Async.RunSynchronously(async { return Console.ReadLine() }, cancellationToken = cancellation)
with | _ ->
return None
}
let receiveUI cancellation (tcpConnection: ITcpConnection) =
let rec loop () =
async {
let! message = readLineAsync cancellation
match message with
| Some msg -> msg |> tcpConnection.Send
| None -> printfn "Chat Session Ended"
return! loop ()
}
loop () |> Async.Start

What is the best way to track the state of an Isolate in Dart?

I'm trying to track whether the isolate is currently running or not (and in the future whether it has errored out) using isolate.addOnExitListener(...). However, the following snippet of code is not working how I would expect:
items.forEach((name, item) async {
Isolate isolate = await Isolate.spawnUri(...);
item.status = "running";
ReceivePort receivePort = new ReceivePort();
isolate.addOnExitListener(receivePort.sendPort);
receivePort.listen((message){
if (message == null) {
print("Item exited: ${item.name}");
item.status = "stopped";
}
});
});
The "items" map contains 3 values, each with a distinct name: item1, item2, item3
When I run this code, the only output I get is:
"Item exited: item3"
I expected the following output (not necessarily in order since isolates are asynchronous):
"Item exited: item1"
"Item exited: item2"
"Item exited: item3"
Here is the code being run in the isolates:
import 'dart:io';
main(List args) {
print('Hello world: standard out!');
stderr.writeln('Hello world: standard error!');
}
It seems like the closure is being lost. Am I doing something wrong here? Is there a better way to track the state of an isolate?
Thanks in advance!
If you want to make absolutely sure that you can install onExit and onError listeners in an isolate before any of the isolate's code executes, then you can spawn the isolate paused. See documentation about spawnUri.
Here is an example:
var isolate = await Isolate.spawnUri(myUri, args, message, paused: true);
var receivePort = new ReceivePort();
isolate.addOnExitListener(receivePort.sendPort);
receivePort.listen((message){
if (message == null) { // A null message means the isolate exited
print("Item exited: ${item.name}");
item.status = "stopped";
}
});
isolate.resume(isolate.pauseCapability);
Once you have registered the appropriate listeners, you can start the newly created isolate with resume.
This is very similar to the suggestion of an initial handshake, but in this case it is builtin to the library.
Hope this helps,
-Ivan
I had the same behavior when the isolate didn't do anything notable (just one print statement). It seems it exited before the onExitListener was registered.
DartDoc of onExitListener says
If the isolate is already dead, no message will be sent.
The isolate code
import 'dart:async' show Future, Stream;
void main(List<String> args) {
new Future.delayed(new Duration(milliseconds: 500),
() =>print('isolate ${args}'));
}
With the additional delay I got the desired on exit notification.
The delay needs to be quite high :-(.
You can do some initial handshake to ensure the isolate doesn't exit before everything is set up properly
import 'dart:isolate';
import 'dart:async' show Future, Stream, Completer;
import 'dart:io' as io;
class Item {
String name;
String status;
Item(this.name);
}
void main() {
final items = {'a': new Item('a'), 'b': new Item('b'), 'c': new Item('c')};
items.forEach((name, item) async {
ReceivePort receivePort = new ReceivePort();
SendPort sendPort = receivePort.sendPort;
Isolate isolate = await Isolate.spawnUri(
Uri.parse('isolate.dart'), [sendPort, name], null);
receivePort.listen((message) {
if (message is SendPort) {
message.send('connected');
} else if (message == null) {
print("Item exited: ${item.name}");
item.status = "stopped";
} else {
print("Message: ${message}");
}
});
isolate.addOnExitListener(receivePort.sendPort);
item.status = "running";
});
}
import 'dart:isolate';
void main(List<String> args) {
SendPort sendPort = (args[0] as SendPort);
var receivePort = new ReceivePort();
sendPort.send(receivePort.sendPort);
// keeps the isolate alive at least until the first messgae arrives
receivePort.first.then((e) => print('isolate received: $e'));
}

In template reactive context, how can I retrieve thrown error from collection?

I have the following code:
GetPublication = new Meteor.Collection 'get-publication'
Meteor.autorun ->
Meteor.subscribe 'get-publication', Session.get 'currentPublicationId', {
onReady: console.log "ready"
onError: (error) -> console.error "error", error
}
Template.publication.publication = ->
# How to know here what was an error thrown in subscription?
JSON.stringify GetPublication.findOne()
I have a custom collection:
Meteor.publish 'get-publication', (publicationId) ->
self = this
self.ready()
self.error new Meteor.Error 500, "Test"
I would like to output the message in the template with the content thrown in the subscription, instead of the (empty) publication collection result.
Furthermore, why onReady and onError handlers are not called?
You're assigning the result of console.log("ready") to onReady. The correct syntax is:
onReady: -> console.log "ready"
If you want to print the error you're given, I imagine you'd want to store what you get from the error callback in a variable (such as Session) and then print that in the template. Something like this:
Meteor.autorun ->
Meteor.subscribe 'get-publication', Session.get 'currentPublicationId', {
onReady: -> console.log "ready"
onError: (error) -> Session.set "get-publication-error", error
}
Template.publication.publicationError = ->
JSON.stringify(Session.get "get-publication-error")

Resources