   ,
     Publication.PUBLIC_FIELDS()
 
-Meteor.publish 'my-publications', ->
+# TODO: Should we use try/except around the code so that if there is any exception we stop handlers?
+publishUsingMyLibrary = (publish, selector, options) ->
   # There are moments when two observes are observing mostly similar list
   # of publications ids so it could happen that one is changing or removing
   # publication just while the other one is adding, so we are making sure


    changed: (id, fields) =>
      # Person should already be added
      assert.notEqual currentPersonId, null

      publishPublications _.pluck fields.library, '_id'

    removed: (id) =>
      # We cannot remove the person if we never added the person before
      assert.notEqual currentPersonId, null

      handlePublications.stop() if handlePublications
      handlePublications = null

      currentPersonId = null
      removePublications _.pluck currentPublications, '_id'

  @ready()

  @onStop =>
    handlePersons.stop() if handlePersons
    handlePublications.stop() if handlePublications

# We could try to combine my-publications and my-publications-importing,
# but it is easier to have two and leave to Meteor to merge them together
Meteor.publish 'my-publications-importing', ->
  Publications.find
    'importing.person._id': @personId

  currentPersonId = null # Just for asserts
  handlePublications = null

  publishPublications = (newLibrary) =>
    newLibrary ||= []

    initializing = true
    initializedPublications = []

    oldHandlePublications = handlePublications
    handlePublications = Publications.find(selector(newLibrary), options).observeChanges
      added: (id, fields) =>
        initializedPublications.push id if initializing

        return if currentPublications[id]
        currentPublications[id] = true

        publish.added 'Publications', id, fields

      changed: (id, fields) =>
        return if not currentPublications[id]

        publish.changed 'Publications', id, fields

      removed: (id) =>
        return if not currentPublications[id]
        delete currentPublications[id]

        publish.removed 'Publications', id

    initializing = false

    # We stop the handle after we established the new handle,
    # so that any possible changes hapenning in the meantime
    # were still processed by the old handle
    oldHandlePublications.stop() if oldHandlePublications

    # And then we remove those which are not published anymore
    for id in _.difference _.keys(currentPublications), initializedPublications
      delete currentPublications[id]
      publish.removed 'Publications', id

  handlePersons = Persons.find(
    _id: publish.personId
  ,
    fields:
      # id field is implicitly added
