kandi background
Explore Kits

sqlbrite | lightweight wrapper around SQLiteOpenHelper | Reactive Programming library

 by   square Java Version: 0.6.2 License: Apache-2.0

 by   square Java Version: 0.6.2 License: Apache-2.0

Download this library from

kandi X-RAY | sqlbrite Summary

sqlbrite is a Java library typically used in Programming Style, Reactive Programming applications. sqlbrite has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. However sqlbrite has 5 bugs. You can download it from GitHub.
A lightweight wrapper around SupportSQLiteOpenHelper and ContentResolver which introduces reactive stream semantics to queries.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • sqlbrite has a highly active ecosystem.
  • It has 4657 star(s) with 442 fork(s). There are 222 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 5 open issues and 121 have been closed. On average issues are closed in 71 days. There are no pull requests.
  • It has a negative sentiment in the developer community.
  • The latest version of sqlbrite is 0.6.2
sqlbrite Support
Best in #Reactive Programming
Average in #Reactive Programming
sqlbrite Support
Best in #Reactive Programming
Average in #Reactive Programming

quality kandi Quality

  • sqlbrite has 5 bugs (0 blocker, 0 critical, 2 major, 3 minor) and 70 code smells.
sqlbrite Quality
Best in #Reactive Programming
Average in #Reactive Programming
sqlbrite Quality
Best in #Reactive Programming
Average in #Reactive Programming

securitySecurity

  • sqlbrite has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • sqlbrite code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
sqlbrite Security
Best in #Reactive Programming
Average in #Reactive Programming
sqlbrite Security
Best in #Reactive Programming
Average in #Reactive Programming

license License

  • sqlbrite is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
sqlbrite License
Best in #Reactive Programming
Average in #Reactive Programming
sqlbrite License
Best in #Reactive Programming
Average in #Reactive Programming

buildReuse

  • sqlbrite releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • sqlbrite saves you 1394 person hours of effort in developing the same functionality from scratch.
  • It has 3118 lines of code, 261 functions and 42 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
sqlbrite Reuse
Best in #Reactive Programming
Average in #Reactive Programming
sqlbrite Reuse
Best in #Reactive Programming
Average in #Reactive Programming
Top functions reviewed by kandi - BETA

kandi has reviewed sqlbrite and discovered the below as its top functions. This is intended to give you an instant insight into sqlbrite implemented functionality, and help decide if they suit your requirements.

  • Registers dialog with new instance
  • Updates rows in a table .
  • Overridden to add new options menu items .
  • Provide a JDBC database .
  • Get a view at a specific position
  • On create the content fragment .
  • Resolves a cursor to an Optional instance using the provided mapping function .
  • Wrap database helper .
  • Logs a message .
  • This method is called when the application is paused .

sqlbrite Key Features

A lightweight wrapper around SQLiteOpenHelper which introduces reactive stream semantics to SQL operations.

Usage

copy iconCopydownload iconDownload
SqlBrite sqlBrite = new SqlBrite.Builder().build();

Download

copy iconCopydownload iconDownload
implementation 'com.squareup.sqlbrite3:sqlbrite:3.2.0'

License

copy iconCopydownload iconDownload
Copyright 2015 Square, Inc.

Observable do not call onComplete (sqlbrite - mapToOneOrDefault)

copy iconCopydownload iconDownload
fun BriteDatabase.selectDayTimelineRecord(dayTimestamp: Long) =
    createQuery(table_timeline, selectWDayRecords(dayTimestamp))
        .mapToOneOrDefault(StatItem(dayTimestamp, 0)) { cursor -> cursor.mapTimelineStat() }
        .take(1)

RxJava2 query SQLite

copy iconCopydownload iconDownload
fun queryInvoices(): List<Invoice>{
    val results = arrayListOf<Invoice>()
    // your logic to retrieve data from SQLite
    return results
  }
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
fun fetchInvoices() {
  rxFetchData(::queryInvoices)
      .subscribeOn(io())
      .observeOn(mainThread())
      .subscribe(
          { data ->
            Log.i("onSuccess", " fetched ${data.size} invoices")
          },
          { error ->
            error.printStackTrace()
          })
}
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
public Single<List<Invoice>> invoices(){
  return Single.fromCallable(this::fetchInvoices);
}
-----------------------
fun queryInvoices(): List<Invoice>{
    val results = arrayListOf<Invoice>()
    // your logic to retrieve data from SQLite
    return results
  }
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
fun fetchInvoices() {
  rxFetchData(::queryInvoices)
      .subscribeOn(io())
      .observeOn(mainThread())
      .subscribe(
          { data ->
            Log.i("onSuccess", " fetched ${data.size} invoices")
          },
          { error ->
            error.printStackTrace()
          })
}
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
public Single<List<Invoice>> invoices(){
  return Single.fromCallable(this::fetchInvoices);
}
-----------------------
fun queryInvoices(): List<Invoice>{
    val results = arrayListOf<Invoice>()
    // your logic to retrieve data from SQLite
    return results
  }
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
fun fetchInvoices() {
  rxFetchData(::queryInvoices)
      .subscribeOn(io())
      .observeOn(mainThread())
      .subscribe(
          { data ->
            Log.i("onSuccess", " fetched ${data.size} invoices")
          },
          { error ->
            error.printStackTrace()
          })
}
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
public Single<List<Invoice>> invoices(){
  return Single.fromCallable(this::fetchInvoices);
}
-----------------------
fun queryInvoices(): List<Invoice>{
    val results = arrayListOf<Invoice>()
    // your logic to retrieve data from SQLite
    return results
  }
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
fun fetchInvoices() {
  rxFetchData(::queryInvoices)
      .subscribeOn(io())
      .observeOn(mainThread())
      .subscribe(
          { data ->
            Log.i("onSuccess", " fetched ${data.size} invoices")
          },
          { error ->
            error.printStackTrace()
          })
}
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
public Single<List<Invoice>> invoices(){
  return Single.fromCallable(this::fetchInvoices);
}
-----------------------
fun queryInvoices(): List<Invoice>{
    val results = arrayListOf<Invoice>()
    // your logic to retrieve data from SQLite
    return results
  }
fun <T>rxFetchData(func: () -> List<T>): Single<List<T>> = Single.fromCallable(func)
fun fetchInvoices() {
  rxFetchData(::queryInvoices)
      .subscribeOn(io())
      .observeOn(mainThread())
      .subscribe(
          { data ->
            Log.i("onSuccess", " fetched ${data.size} invoices")
          },
          { error ->
            error.printStackTrace()
          })
}
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.schedulers.Schedulers.io
public Single<List<Invoice>> invoices(){
  return Single.fromCallable(this::fetchInvoices);
}

onNext of the Subscribe method not emitting items after using the ZIP WITH operator in RxJava?

copy iconCopydownload iconDownload
mLocalDataSource
  .getVideoCategory()
  .compose(RxUtils.applySchedulers())
  .flatMap(new Function<List<VideoResponse>, 
              ObservableSource<List<VideoResponse>>>() {
                    @Override
                     public ObservableSource<List<VideoResponse>> apply(List<VideoResponse> videoResponses) throws Exception {
                             return Observable.just(videoResponses)
                                    .concatMap(videoResponses1 -> Observable.fromIterable(videoResponses1)
                                    .concatMap(videoResponse -> Observable.just(videoResponse)
                                    .concatMap(videoResponse1 -> {
                                                Integer videoId = videoResponse1.getId();
                                                return Observable.just(videoResponse1)
                                                      .zipWith(getVideoFilesList(videoId), new BiFunction<VideoResponse, List<VideoFiles>, VideoResponse>() {
                                                                @Override
                                                                public VideoResponse apply(VideoResponse videoResponse1, List<VideoFiles> videoFiles) throws Exception {
                                                                        videoResponse1.setFiles(videoFiles);
                                                                        Timber.d("Video Responses == >  %s",videoResponse1);
                                                                        return videoResponse1;
                                                                        }
                                                                    });
                                                     })))
                                      .toList()
                                      .toObservable()
                                     .observeOn(AndroidSchedulers.mainThread());
                            }
                        }); 

Not able to download multiple video files from json and set the download path to the same list

copy iconCopydownload iconDownload
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
@Override
public Observable<List<VideoResponse>> getVideoResponse() {
    return service.getVideoResponseFromServer()
            .subscribeOn(Schedulers.io())
            .map(this::setVideoLocalPath)
            .observeOn(AndroidSchedulers.mainThread());
            .doOnSubscribe(disposable -> Timber.d("*** Video Sync Started....."))
            .doOnError(throwable -> Timber.d("*** Video Sync Failed ...."))
            .doOnComplete(() -> Timber.d(" *** Video Sync Complete...."));
}
-----------------------
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
@Override
public Observable<List<VideoResponse>> getVideoResponse() {
    return service.getVideoResponseFromServer()
            .subscribeOn(Schedulers.io())
            .map(this::setVideoLocalPath)
            .observeOn(AndroidSchedulers.mainThread());
            .doOnSubscribe(disposable -> Timber.d("*** Video Sync Started....."))
            .doOnError(throwable -> Timber.d("*** Video Sync Failed ...."))
            .doOnComplete(() -> Timber.d(" *** Video Sync Complete...."));
}
-----------------------
....
.compose(RxUtils.applySchedulers())
.map(this::setVideoLocalPath)
...
static Observable.Transformer schedulersTransformer = new Observable.Transformer<Object, Object>() {
    @Override public Observable<Object> call(Observable<Object> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
};
....
.map(this::setVideoLocalPath)
.compose(RxUtils.applySchedulers())
...
-----------------------
....
.compose(RxUtils.applySchedulers())
.map(this::setVideoLocalPath)
...
static Observable.Transformer schedulersTransformer = new Observable.Transformer<Object, Object>() {
    @Override public Observable<Object> call(Observable<Object> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
};
....
.map(this::setVideoLocalPath)
.compose(RxUtils.applySchedulers())
...
-----------------------
....
.compose(RxUtils.applySchedulers())
.map(this::setVideoLocalPath)
...
static Observable.Transformer schedulersTransformer = new Observable.Transformer<Object, Object>() {
    @Override public Observable<Object> call(Observable<Object> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
};
....
.map(this::setVideoLocalPath)
.compose(RxUtils.applySchedulers())
...

RxJava2 concat operator doesn't return appropriate stream

copy iconCopydownload iconDownload
mQuakesLocalDataSource.getQuakes()
.flatMap(list -> {
    if (list.isEmpty()) {
        return mQuakesRemoteDataSource.getQuakes();
    }
    return Single.just(list);
})

Errors when testing database repository - SQLBrite, SQLDelight

copy iconCopydownload iconDownload
@Before
public void setUp() {
    context = InstrumentationRegistry.getTargetContext();
    context.deleteDatabase(MyDbHelper.DATABASE_NAME);
    mDataRepository = new DataRepository(InstrumentationRegistry.getTargetContext());
}

// In DataRepository.java
DataRepository(Context context) {
    SqlBrite sqlBrite = new SqlBrite.Builder().build();
    MyDbHelper helper = new MyDbHelper(context);
    briteDatabase = sqlBrite.wrapDatabaseHelper(helper, Schedulers.io());
    locationManger = new LocationManger(briteDatabase.getWritableDatabase());
    runManager = new RunManager(briteDatabase.getWritableDatabase());
}

// In MyDbHelper.java
MyDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

Repository pattern with SqlBrite/SqlDelight(Offline database) and Retrofit(Http request)

copy iconCopydownload iconDownload
     Observable<List<Item>> db = getItemsFromDbById(id)
             .filter(items -> items != null && items.size() > 0);
-----------------------
class Data<T> {

    static final int STATE_LOCAL = 0;
    static final int STATE_SERVER = 1;

    private T data;
    private int state;

    Data(T data, int state) {
        this.data = data;
        this.state = state;
    }

    public int getState() { return state; }

    public T getData() { return data; }
}
public Observable<Model> getData(long id) {

    // Used to cache data and compare it with server data, so we can avoid unnecessary UI updates
    Subject<Data<Model>> publishSubject = BehaviorSubject.create();
    publishSubject.onNext(new Data<>(null, Data.STATE_LOCAL));

    Observable<Data<Model>> server = getRequest()
            .map(items -> new Data<>(items, Data.STATE_SERVER))
            // Here we are combining data from server and our `BehaviorSubject`
            // If any one has ideas how to do this without the subject, I'll be glad to hear it.
            .flatMap(items -> Observable.zip(publishSubject.take(1), Observable.just(items), Pair::new))
            .flatMap(oldNewPair -> {
                // Here we are comparing old and new data to see if there was any new data returned from server
                Data<Model> prevData = oldNewPair.first;
                Data<Model> newData = oldNewPair.second;
                //Could be any condition to compare the old and new data
                if (prevData.data != null && prevData.data.updated_at() == newData.data.updated_at()) 
                    return Observable.just(prevData);
                else
                    return database.insert(tableName(), contentValues(newData));

                return getFromDb(id)
                        .map(item -> new Data<>(item, Data.STATE_LOCAL))
                        .onErrorResumeNext(server)
                        .doOnNext(item -> {
                            publishSubject.onNext(item);
                            if (item.getState() == Data.STATE_LOCAL)
                                server.subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe();
                        })
                        .map(item -> item.data);
}
-----------------------
class Data<T> {

    static final int STATE_LOCAL = 0;
    static final int STATE_SERVER = 1;

    private T data;
    private int state;

    Data(T data, int state) {
        this.data = data;
        this.state = state;
    }

    public int getState() { return state; }

    public T getData() { return data; }
}
public Observable<Model> getData(long id) {

    // Used to cache data and compare it with server data, so we can avoid unnecessary UI updates
    Subject<Data<Model>> publishSubject = BehaviorSubject.create();
    publishSubject.onNext(new Data<>(null, Data.STATE_LOCAL));

    Observable<Data<Model>> server = getRequest()
            .map(items -> new Data<>(items, Data.STATE_SERVER))
            // Here we are combining data from server and our `BehaviorSubject`
            // If any one has ideas how to do this without the subject, I'll be glad to hear it.
            .flatMap(items -> Observable.zip(publishSubject.take(1), Observable.just(items), Pair::new))
            .flatMap(oldNewPair -> {
                // Here we are comparing old and new data to see if there was any new data returned from server
                Data<Model> prevData = oldNewPair.first;
                Data<Model> newData = oldNewPair.second;
                //Could be any condition to compare the old and new data
                if (prevData.data != null && prevData.data.updated_at() == newData.data.updated_at()) 
                    return Observable.just(prevData);
                else
                    return database.insert(tableName(), contentValues(newData));

                return getFromDb(id)
                        .map(item -> new Data<>(item, Data.STATE_LOCAL))
                        .onErrorResumeNext(server)
                        .doOnNext(item -> {
                            publishSubject.onNext(item);
                            if (item.getState() == Data.STATE_LOCAL)
                                server.subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe();
                        })
                        .map(item -> item.data);
}

Android app install with Failure [INSTALL_FAILED_DEXOPT] Android 2.3.x devices

copy iconCopydownload iconDownload
com.fasterxml.jackson.core:jackson-databind

How to convert a Android SqlBrite model class to implement Parcelable

copy iconCopydownload iconDownload
        mRecipeListRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerViewState);

Rxjava2 approach similar to backpressure for BiFunction

copy iconCopydownload iconDownload
 .combineLatest(srcA, srcB, (a, b) -> Pair.of(a, b))
 .onBackpressureLatest()
 .observeOn(Schedulers.computation(), false, 1)
 .map(pair -> compute(pair))
 .observeOn(AndroidSchedulers.mainThread())
 ...

Community Discussions

Trending Discussions on sqlbrite
  • Flutter: StreamBuilder stream not updating
  • SQLDelight - Emit on Parent Tables when Child Tables are Modified
  • Observable do not call onComplete (sqlbrite - mapToOneOrDefault)
  • RxJava2 query SQLite
  • UI freezes while adding many views programmatically
  • onNext of the Subscribe method not emitting items after using the ZIP WITH operator in RxJava?
  • Not able to download multiple video files from json and set the download path to the same list
  • RxJava2 concat operator doesn't return appropriate stream
  • Errors when testing database repository - SQLBrite, SQLDelight
  • SQLBrite how to pass parameter to createQuery
Trending Discussions on sqlbrite

QUESTION

Flutter: StreamBuilder stream not updating

Asked 2021-May-04 at 17:29

My StreamBuilder didn't refresh after changes to the stream, and also the stream does not update too, when fetching data from Firebase and store it to local SQLite database;

And here is my code for listen to data changes from Firebase and then write those new chats to local:

    /// LISTEN TO THE STREAM FROM FIREBASE AND THEN WRITE THE NEW MESSAGES TO THE LOCAL DATASE

  // Fetch normal messages
      firestore.fetchMessagesStream(chatRoomId).listen((event) async {
        for (QueryDocumentSnapshot message in event.docs) {
           _database.insert(
            'Messages',
            message.data()!,
            conflictAlgorithm: sql.ConflictAlgorithm.replace,
          );
        }
      });
      // Fetch calls
      firestore.fetchCallsStream(chatRoomId).listen((event) async {
        for (QueryDocumentSnapshot call in event.docs) {
          _database.insert(
            'Calls',
            call.data()!,
            conflictAlgorithm: sql.ConflictAlgorithm.replace,
          );
      // Fetch posts
      firestore.fetchPostsStream(chatRoomId).listen((event) async {
        for (QueryDocumentSnapshot post in event.docs) {
          _database.insert(
            'Posts',
            post.data()!,
            conflictAlgorithm: sql.ConflictAlgorithm.replace,
          );
        }
      });

And here the code for fetching data from the Local SQLite database:

/// STREAM FOR LISTENING THE CHANGES IN THE LOCAL DATABASE

Rx.combineLatest3(
      _database.query(
       'Messages',
        where: 'chatRoomId = ?',
        whereArgs: [chatRoomId],
        ).asStream(), // Returns the stream of the Messages Table in local databases
      _database.query(
        'Posts',
        where: 'chatRoomId = ?',
        whereArgs: [chatRoomId],
     ).asStream(), // Returns the stream of the Posts Table in local databases
      _database.query(
        'Calls',
        where: 'chatRoomId = ?',
        whereArgs: [chatRoomId],
       ).asStream(), // Returns the stream of the Calls Table in local databases
      (List<Map<String, dynamic>> streamingMessages,
          List<Map<String, dynamic>> streamingPosts,
          List<Map<String, dynamic>> streamingCalls) {
        /// VERY IMPORTANT: THE FOLLOWING PRINT STATEMENT WILL BE PRINT OUT EVERYTIME A NEW CHAT ARRIVE
        /// VERY IMPORTANT: THE FOLLOWING PRINT STATEMENT WILL BE PRINT OUT EVERYTIME A NEW CHAT ARRIVE
        /// VERY IMPORTANT: THE FOLLOWING PRINT STATEMENT WILL BE PRINT OUT EVERYTIME A NEW CHAT ARRIVE
        /// VERY IMPORTANT: THE FOLLOWING PRINT STATEMENT WILL BE PRINT OUT EVERYTIME A NEW CHAT ARRIVE
        /// VERY IMPORTANT: THE FOLLOWING PRINT STATEMENT WILL BE PRINT OUT EVERYTIME A NEW CHAT ARRIVE
        print('MySqlite: chat stream changes!');

        final List<dynamic> contents = [...streamingMessages, ...streamingPosts, ...streamingCalls];

        return contents;
      },
    );
  }

The expected timeline when sent a new message will be:

User sent a message --> trigger changes in Firebase --> trigger the LOCAL SQLite to add new data --> Because our SQLite have added new chats, so our ChatScreen should refresh & also a new debug message: 'MySqlite: chat stream changes!' should be printed out again in the console since the ChatScreen is listening to the SQLite Database Stream.

But the actual result is:

User sent a message --> trigger changes in Firebase successfully --> but I DIDN'T see the screen being refreshed NOR new debug message in the console...

I've been struggle with this issue for days, and I don't know why the result is not what I want, if I let the ChatScreen to directly listen to Firebase, it works!*

UPDATE:

I just found out that if I rebuild the ChatScreen (pop the screen, and then open it again), or setState when sending a new message, I can see the new message, it proves that the Message did go into the SQLite database after sent, but it just did not trigger the StreamBuilder. So it might be something wrong with the Fetching Stream.

ANSWER:

I just found out that the SQLite.query function cannot be fetched as a Stream, and I thought I can by using "asStream" method, but this does not do anything, it is a missed feature that SQLite package didn't implement yet, so I add the sqlbrite package that works as a wrapper of the original SQLite package, and it has some additional feature such as querying data as a Stream. ^_^

ANSWER

Answered 2021-May-04 at 17:27

I just found out that the SQLite.query function cannot be fetched as a Stream, and I thought I can by using "asStream" method, but this does not do anything, it is a missed feature that SQLite package didn't implement yet, so I add the sqlbrite package that works as a wrapper of the original SQLite package, and it has some additional feature such as querying data as a Stream. ^_^

Source https://stackoverflow.com/questions/67362156

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install sqlbrite

For the kotlin module that adds extension functions to Observable<Query>:. Snapshots of the development version are available in [Sonatype’s snapshots repository][snap].

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Reactive Programming Libraries
Compare Reactive Programming Libraries with Highest Support
Compare Reactive Programming Libraries with Highest Quality
Compare Reactive Programming Libraries with Highest Security
Compare Reactive Programming Libraries with Permissive License
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.